Let's explore Go's built-in support for complex numbers via thecomplex64
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"
"math"
)
func Cbrt(x complex128) complex128 {
z := x
for i := 0; i < 10; i++ {
z = (2*z + x/(z*z))/3
}
return z
}
func main() {
fmt.Println(Cbrt(2))
fmt.Println(math.Cbrt(2))
}
有疑问加站长微信联系(非本文作者)