Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

square root algorithm C++

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;
}
like image 871
csciXAV_12 Avatar asked Jan 15 '15 06:01

csciXAV_12


People also ask

How do you write square root in C?

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));

What is the algorithm for square root?

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

What is the C program function for square root?

(Square Root) In the C Programming Language, the sqrt function returns the square root of x.

How do you write a program to find the square root of a number in C++?

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 .


1 Answers

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.

like image 147
ale64bit Avatar answered Oct 15 '22 10:10

ale64bit