[Swift演算法]巴比倫法(牛頓迭代法)求平方根

來源:互聯網
上載者:User

標籤:

 

數學原理推導:f(X) = X2 - n   ---公式(1) n為要求平方根的數值 比如 要求100的平方根 n = 100;所以問題就轉換成了求f(X)的零點問題了 f(Xn)的導數就是Xn+1 的斜率所以就有了公式 所以 Xn+1 = Xn - f(Xn)/f‘(Xn) 代入 公式1 f(Xn)=X2  -nf‘(Xn)=2XXn+1 = Xn - (Xn2 - n) / (2Xn)   = Xn - 1/2 (Xn-n / Xn)   = 1 / 2 (Xn + n / Xn)  Xn 是被猜測的數字 n 是要求平方根的數值經過多次迭代之後 Xn  Swift 實現代碼:  
import UIKitfunc babylonianMethod (toSqrt number: Double, epsilon: Double) -> Double{    // epsilon 是精度控制    var Xn0: Double = 1    var Xn1: Double = (Xn0 + number / Xn0) / 2        while( fabs(Xn0 - Xn1) > epsilon) {        Xn0 = Xn1        Xn1 = (Xn0 + number / Xn0) / 2    }    return Xn1    }babylonianMethod(toSqrt: 2, 1e-10)

 

 

[Swift演算法]巴比倫法(牛頓迭代法)求平方根

相關文章

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.