I can not figure out why this algorithm enters an infinite loop if the number entered is over 12 digits. Can anyone see why it will never end? Thanks. I just updated the algorithm to use the fabs() function and still get an infinite loop.
double squareroot(double x)
{ /* computes the square root of x */
/* make sure x is not negative .. no math crimes allowed! */
assert( x >= 0 );
if (x==0) return 0;
/* the sqrt must be between xhi and xlo */
double xhi = x;
double xlo = 0;
double guess = x/2;
/* We stop when guess*guess-x is very small */
while (abs(guess*guess-x) > 0.00001 )
{
if (guess*guess > x){
xhi = guess;
}
else {
xlo = guess;
}
guess = (xhi + xlo)/2;
}
return guess;
}
The sqrt() function is defined in math. h header file. To find the square root of int , float or long double data types, you can explicitly convert the type to double using cast operator. int x = 0; double result; result = sqrt(double(x));
Algorithm. Take a reasonable guess (approximate root) for the square root. Add the approximate root with the original number divided by the approximate root and divide by 2. Continue step 2 until the difference in the approximate root along the iterations is less than the desired value (or precision value).
(Square Root) In the C Programming Language, the sqrt function returns the square root of x.
C++ sqrt() The sqrt() function in C++ returns the square root of a number. This function is defined in the cmath header file. Mathematically, sqrt(x) = √x .
I believe you should use relative error for the termination, and not the absolute error.
while (abs((guess*guess-x) / guess) > 0.00001)
Otherwise it will take very long time (it's not an infinite loop) to compute square root of very long values.
http://en.wikipedia.org/wiki/Approximation_error
Cheers!
EDIT: moreover, as pointed below in the comments, it is worthy to check if the guess
was already guessed in order to avoid infinite loop with some specific corner cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With