I am trying to compute the square root of a number using function containing a while loop. Within the conditions of the while loop, I want to compare the absolute value of the ratio of the two values, the guessed square root and the number, to 1. However, whenever I run the program, I keep get an infinite loop outputting 1.414214. Any help? Thanks.
// Function to calculate the absolute value of a number
#include <stdio.h>
float absoluteValue (float x)
{
if ( x < 0 )
x = -x;
return (x);
}
// Function to compute the square root of a number
float squareRoot (float x, const float epsilon)
{
float guess = 1.0;
while ( absoluteValue ((guess * guess) / x) != epsilon ) {
guess = ( (x / guess) + guess ) / 2.0;
printf("%f\n", guess);
}
return guess;
}
int main (void)
{
printf ("squareRoot (2.0) = %f\n", squareRoot (2.0, 1.0));
printf ("squareRoot (144.0) = %f\n", squareRoot (144.0, 1.0));
printf ("squareRoot (17.5) = %f\n", squareRoot (17.5, 1.0));
return 0;
}