如何在Go中扎根?

我正在使用牛顿方法在Google Go中编写多维数据集根函数。我想使用math /检查结果cmplx.Pow(),但是对于我自己的一生,我不知道该怎么做。我该怎么做呢?


Cats萌萌
浏览 187回答 3
3回答

呼如林

你试过了myCubicRootOfx = Pow(x, 1.0/3)吗?编辑:感谢Jason McCreary评论:我们不能将其1/3用作第二个参数,Pow因为这是整数除法,因此不会产生预期的1/3值。通过使用1.0/3或1/3.0等,我们可以有效地产生一个带有0.333333 ...值的浮点数。

aluckdog

在Go Tour练习47中,我使用牛顿方法编写了立方根函数。(Cbrt1和Cbrt)下面的两个功能可能会有所帮助。package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "math/cmplx")// Newton's method cube root function that hopes for//&nbsp; &nbsp;convergence within 20 iterationsfunc Cbrt1(x complex128) complex128 {&nbsp; &nbsp; var z complex128 = x&nbsp; &nbsp; for i:= 0; i < 20; i++ {&nbsp; &nbsp; &nbsp; &nbsp; z = z - ((z*z*z - x) / (3.0*z*z))&nbsp; &nbsp; }&nbsp; &nbsp; return z}// Newton's method cube root function that runs until stablefunc Cbrt(x complex128) complex128 {&nbsp; &nbsp; var z, z0 complex128 = x, x&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; z = z - ((z*z*z - x) / (3.0*z*z))&nbsp; &nbsp; &nbsp; &nbsp; if cmplx.Abs(z - z0) < 1e-10 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; z0 = z&nbsp; &nbsp; }&nbsp; &nbsp; return z}func main() {&nbsp; &nbsp; fmt.Println(Cbrt(2.0) , "should match" , cmplx.Pow(2, 1.0/3.0))}

忽然笑

当您使用牛顿法时,我想您是从一个正实数开始的。因此,您不需要复数。你可以简单地做package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "math")func main() {&nbsp; &nbsp; x := 100.0&nbsp; &nbsp; root := math.Pow(x, 1.0/3.0)&nbsp; &nbsp; fmt.Println(root)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go