C Language Standard library:
http://www.cplusplus.com/reference/cmath/
In an interval, each time the square of the middle number to test, if large, then try the middle of the left interval, if it is small, then take the middle of the right interval to try. For example sqrt (16) results, you first try (0+16)/2=8,8*8=64,64 than 16, then move to the left, try (0+8)/2=4,4*4=16 just, got the correct result sqrt (16) = 4.
Implementation of the first time I did not carry out precision control, resulting in some can not complete the root of the number of operations, but also forget the judgment of non-integers. Code 1 for the corrected code, followed by code 2 for the first write code, posted here for comparison reminders.
Code Listing 1:
ESP is often used in C + + to control iterative precision, which is a constant declared by a function program, and is an infinitely small value in calculus.
float esp=0.000000;
Double sqrt (double x)
{
Double down,up,n,last;
down=0;
Up=x;
n= (Down+up)/2;
if (x<=0)
return x;
while ((n*n!=x) &&abs (last-n) >esp)
{
if (n*n<x)
{
Down=n;
Last=n;
n= (Down+up)/2;
}
Else
{
Up=n;
Last=n;
n= (Down+up)/2;
}
}
return n;
}
Code Listing 2:
Double sqrt (double x)
{
Double down,up,n;
down=0;
Up=x;
n= (Down+up)/2;
while (N*N!=X)
{
if (n*n<x)
{
Down=n;
n= (Down+up)/2;
}
Else
{
Up=n;
n= (Down+up)/2;
}
}
return n;
}
Reference: http://www.2cto.com/kf/201206/137256.html
The realization of the calculation function of sqrt () square root----two-point method