A Tour of Go 47 Advanced Exercise: Complex cube roots

演習:ニュートン法を使った複素数( complex )の立方根の計算を実装

package main

import (
    "fmt"
    "math/cmplx"
)

func square(x complex128) complex128 {
    return x*x
}

func cube(x complex128) complex128 {
    return x*x*x
}

func enough(x,y complex128 ) bool {
    const tolerance = 0.0001   
    return cmplx.Abs(x-y) > tolerance 
}

func Cbrt(x complex128) complex128 {
    z := 1.0+0i
    for pz := 0+0i; enough(pz,z); {
        pz = z
        z -= (cube(z)-x)/(3*square(z))
    }
    return z
}

func main() {
    fmt.Println(cmplx.Pow(Cbrt(2),3))
}