{{ message }}

Instantly share code, notes, and snippets.

# tetsuok/complex_cube_root.go

Created Apr 2, 2012
An answer of the advanced exercise: complex cube roots on a tour of Go
 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)) }

### francistm commented Aug 14, 2012

 thansk for giving out these codes ~

### cyxcw1 commented Aug 23, 2013

 thanks, now I know Go has the real function, oh...

### mackross commented Nov 24, 2013

 ``````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)) } ``````

### tkintscher commented May 16, 2014

 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.)) }```

### KarthikNayak commented Jul 3, 2014

 ```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 }```