[Swift algorithm] Babylon law (Newton's iterative method) seeking square root

Source: Internet
Author: User
Tags square root

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.