A Tour of Go 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:

Find the cube root of 2, just to make sure the algorithm works. There is a Pow function in the math/cmplx package.

package main

import "fmt"

func Cbrt(x complex128) complex128 {
    z := complex128(1)
    for i := 1;i < 10;i++{
        z = z - (z*z*z -x)/(3*z*z)
    }
    return z
}

func main() {
    fmt.Println(Cbrt(8))
}

 

posted @ 2014-10-28 07:54  wuhn  阅读(146)  评论(0编辑  收藏  举报