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:
- To find the open square value of x.
- Determines whether x is greater than 1, if greater than 1, the minimum value is 1, and the maximum value is x.
- Determines whether x is less than 1, and if less than 1, the minimum value is x and the maximum value is 1.
- The median value, the square of the computed median minus x is within the allowable range of errors, and if so, returns.
- 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.
- 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:
- An estimate of X's root value, G, equals X.
- Calculates the square of G minus the value of x within the error range.
- If it is, it returns G.
- 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