A Tour of Go系列。如有问题欢迎指出~
这个也没什么好说的,就是试一下内建的复数运算。
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 aPow function in the math/cmplx
package.
代码:
1 package main 2 3 import ( 4 "fmt" 5 "math/cmplx" 6 ) 7 8 func Cbrt(x complex128) complex128 { 9 z:=complex128(1) 10 for i:=0;i<10;i++{ 11 z=z-(z*z*z-x)/(3*z*z) 12 } 13 return z 14 } 15 16 func main() { 17 fmt.Println(Cbrt(2)) 18 fmt.Println(cmplx.Pow(2,1.0/3)) 19 }
将输出:
(1.2599210498948732+0i) (1.259921049894873+0i)
注意一下cmplx.Pow的用法。