這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
二分法
- 求根號5
- 折半:5/2=2.5
- 平方校正: 2.5*2.5=6.25>5,並且得到當前上限2.5
- 再次向下折半:2.5/2=1.25
- 平方校正:1.25*1.25=1.5625<5,得到當前下限1.25
- 再次折半:2.5-(2.5-1.25)/2=1.875
- 平方校正:1.875*1.875=3.515625<5,得到當前下限1.875
牛頓迭代法
可以理解函數f(x) = x²,使f(x) = num的近似解,即x² - num = 0的近似解。
Code
123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
package mainimport ( "fmt" "math")func NewtonSqrt(num float64) float64 { x := num / 2.0 var y float64 = 0 count := 1 for math.Abs(x-y) > 0.00000001{ // fmt.Println(count, x) count += 1 y = x x = (1.0/2.0)*x+(num*1.0)/(x*2.0) } return x}func BinarySqrt(num float64) float64 { y := num/2.0 low := 0.0 up := num count := 1 for math.Abs(y * y - num) > 0.00000001{ // fmt.Println(count, y) count += 1 if y*y > num{ up = y y = low+(y-low)/2 }else{ low = y y = up-(up-y)/2 } } return y}func main() { fmt.Println("math sqrt", math.Sqrt(5)) fmt.Println("Newton sqrt", NewtonSqrt(5)) fmt.Println("binary sqrt", BinarySqrt(5))} |
精度0.00000001,在億分之一;
二分法經過27次迭代;
牛頓法只迭代了3次,是二分法的十倍;
系統sqrt是最快最準的,不知道採用了什麼原理實現的?