go二分法和牛頓迭代法求平方根

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

二分法

  • 求根號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是最快最準的,不知道採用了什麼原理實現的?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.