----- 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.