//Newton iterative method to find square root
1 DoubleMYSQRT (Doublenum)2 {3 Doublex = num/2;4 Doubley =0;5 Do{6x = x/2+num/(2*x);7y = x*x-num;8 if(y<0) y =-y;9} while(y>0.0001);Ten returnx; One } A intMainintargcChar*argv[]) - { -printf"%.3f", Mysqrt (2));//1.414 the return 0; -}
The following explanation is taken from somewhere else and turned around for easy viewing:
The principle of this algorithm is very simple, we just constantly use (x,f (x)) tangent to approximate the root of the equation x^2-a=0. Square root A is actually a positive real roots of x^2-a=0, the derivative of this function is 2x. That is, the tangent slope of the function at any point (x,f (x)) is 2x. So, x-f (x)/(2x) is an approximation that is closer than X. Substituting f (x) =x^2-a gets x (x^2-a)/(2x), i.e. (x+a/x)/2.
Classical algorithm: Newton iterative method to find square root