Mathematical principle derivation: f (x) = x2-n---formula (1) n is a value that requires a square root, such as the square root n = 100, which requires 100, so the problem is converted to the 0 point of F (x), the derivative of f (Xn) is the slope of xn+1 so there is a formula so xn+1 = X N-f (Xn)/F ' (Xn) substituting Formula 1 F (Xn) =x2-nf ' (Xn) =2xxn+1 = Xn-(xn2-n)/(2Xn) = XN-1/2 (Xn-n/Xn) = (Xn + n/xn) Xn is a guessed number n is a value that requires a square root after several iterations of the Xn Swift implementation code:
Import Uikitfunc Babylonianmethod (tosqrt number:double, epsilon:double), double{ //Epsilon is precision controlled var Xn0: Double = 1 var xn1:double = (Xn0 + number/xn0)/2 while (Fabs (XN0-XN1) > Epsilon) { Xn0 = Xn1 Xn 1 = (Xn0 + number/xn0)/2 } return Xn1 }babylonianmethod (tosqrt:2, 1e-10)
[Swift algorithm] Babylon law (Newton's iterative method) seeking square root