A Tour of Go chapter 46
Advanced Exercise: Complex cube roots
Let's explore Go's built-in support for complex numbers via the complex64 and complex128 types. For cube roots, Newton's method amounts to repeating:
z = z - (z ** 3 - x) / (z * z * 3)
Find the cube root of 2, just to make sure the algorithm works. There is a Pow function in the math/cmplx package.
Example
package main import ( "fmt" "math/cmplx" ) func Cbrt(x complex128) complex128 { var z, prez complex128 = x / 3, 0 for cmplx.Abs(z - prez) > 1e-10 { prez = z z = z - (z * z * z - x) / (z * z * 3) } return z } func main() { fmt.Println(Cbrt(2)) fmt.Println(cmplx.Pow(Cbrt(2), 3)) }