Created
April 2, 2012 09:23
-
-
Save tetsuok/2282036 to your computer and use it in GitHub Desktop.
An answer of the advanced exercise: complex cube roots on a tour of Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math/cmplx" | |
) | |
// FIXME: | |
// Currently calculate only real part of the input | |
// complex number. | |
func Cbrt(x complex128) complex128 { | |
z := 1.0 | |
tmp := 0.0 | |
rx := real(x) | |
for i := 0; i < 100000; i++ { | |
tmp = z - (z * z * z - rx) / (3 * z * z) | |
z = tmp | |
// DEBUG | |
// fmt.Printf("i = %d, %g\n", i, tmp) | |
} | |
return complex(tmp, imag(x)) | |
} | |
func main() { | |
fmt.Println(Cbrt(2)) | |
fmt.Println(cmplx.Pow(2, 0.3333333)) | |
} |
thanks, now I know Go has the real function, oh...
func Cbrt(x complex128) complex128 {
z := complex128(1)
for i := 0; i < 10; i++ {
z = z - (((z*z*z)-x)/(3*z*z))
}
return z
}
func main() {
fmt.Println(Cbrt(2))
fmt.Println(cmplx.Pow(2,0.33333333333))
}
In order to take into account roots of negative and imaginary numbers, I did the following:
package main
import "fmt"
import "math/cmplx"
func Cbrt(x complex128) complex128 {
z := complex128(1)
if (imag(x) != 0.) || (real(x) < 0) {
z += 1i
}
for i := 0; i < 30; i++ {
z = z - (z*z*z - x)/(3*z*z)
}
return z
}
func main() {
fmt.Println(Cbrt(2))
fmt.Println(cmplx.Pow(2, 1./3.))
}
func Cbrt(x complex128) complex128 {
z := complex128(1)
for i := 0; i < 100; i++ {
z = z - (cmplx.Pow(z,complex128(3)) - x) / (3 * cmplx.Pow(z, complex128(2)))
}
return z
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thansk for giving out these codes ~