Use Newton Iteration Method to write the square root function sqrt

Source: Internet
Author: User

 ----- Edit by ZhuSenlin HDU

Given a positive number a, the square root of the database function is not required.

Set the square root of x, there is x2 = a, that is, the x2-a = 0. If function f (x) = x2-a, the red function curve is displayed. Take a point (x0, f (x0) at any point in the curve. The tangent equation at this point on the curve is

(1-1)

Returns the intersection of the tangent and the X axis.

(1-2)

 

Because x0 is used as the denominator in the 1-2 formula, do not select 0 as the initial value. The intersection of the obtained x and the x axis is actually an approximation of x, and we can continue iteration with this x benchmark to obtain an x that is more approximate, it depends on the precision you set when the approximation is completed. The iteration of the entire process takes only a few steps to obtain the final result.

The Code is as follows:

double NewtonMethod(double fToBeSqrted){double x = 1.0;while(abs(x*x-fToBeSqrted) > 1e-5){x = (x+fToBeSqrted/x)/2;}return x;}

Of course, we can see that when the abscissa of the initial value is on the right of the intersection of the red curve and the x axis, it is larger than the final result, for example, selecting the initial value x =, we can replace abs (x * x-fToBeSqrted) in the while statement with fToBeSqrted-x * x, which saves the abs operation. Of course, this does not ensure efficiency improvement, because the selection of initial values directly affects the number of iterations.

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.