Open square root algorithm

Source: Internet
Author: User
Tags square root

The root algorithm is available in the library functions of the language, and will be much faster than the one mentioned below.

First: Two-point search method.

Algorithmic logic:

    1. To find the open square value of x.
    2. Determines whether x is greater than 1, if greater than 1, the minimum value is 1, and the maximum value is x.
    3. Determines whether x is less than 1, and if less than 1, the minimum value is x and the maximum value is 1.
    4. The median value, the square of the computed median minus x is within the allowable range of errors, and if so, returns.
    5. If the square of the median value is greater than X, the estimated maximum value is set to medium value. If the square of the median value is less than X, the estimated minimum value is set to X.
    6. Cycle 4-5 steps.

The code is as follows:

1 DoublesqrtDoublez)2 {3     DoubleLow =0;4     DoubleHigh =0;5     Doublex =0;6     if(z==1)7     {8x =1;9         returnx;Ten     } One     if(z<1) A     { -Low =Z; -High =1; the     } -     if(z>1) -     { -Low =1; +High =Z; -     } +     DoubleEPS =0.0000001; A      while(1) at     { -         DoubleMid = (Low+high)/2; -         DoubleTMP = mid*mid; -         if(ABS (TMP-Z) <EPS) -         { -x =mid; in              Break; -         } to         if(tmp >z) +         { -High =mid; the}Else{ *Low =mid; $         }Panax Notoginseng     } -     returnx; the}

Second: Newton iterative method

Algorithmic logic:

    1. An estimate of X's root value, G, equals X.
    2. Calculates the square of G minus the value of x within the error range.
    3. If it is, it returns G.
    4. If not, the value of the estimated G is g= (g+z/g)/2. and re-execute the second step. Until the calculation results conform to the error requirement.

The code is as follows:

1 DoubleSqrt_newton (Doublez)2 {3     DoubleEPS =0.00001;4     Doubleg =Z;5      while(ABS (G*G-Z) >EPS)6     {7g = (g+z/g)/2;8     }9     returnG;Ten}

Open square root algorithm

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.