the usage of the long double
The functions purpose is to calculate the square root of a number using the Newton-Raphson method. I included a printf routine in the while loop so I can see the value of root 2 get closer and closer to the actual value. I originally used float to define epsilon but as I increased the value of epsilon, the value of the return results seem to be cut-off after a certain number of digits. So I decided to switch all the variable to long double, and the program is displaying negative results. How do I fix it?
//Function to calculate the absolute value of a number
#include <stdio.h>
long double absoluteValue (long double x)
{
if (x < 0)
x = -x;
return (x);
}
//Function to compute the square root of a number
long double squareRoot (long double x, long double a)
{
long double guess = 1.0;
while ( absoluteValue (guess * guess - x) >= a){
guess = (x / guess + guess) / 2.0;
printf ("%Lfn ", guess);
}
return guess;
}
int main (void)
{
long double epsilon = 0.0000000000000001;
printf ("nsquareRoot (2.0) = %Lfnnnn", squareRoot (2.0, epsilon));
printf ("nsquareRoot (144.0) = %Lfnnnn", squareRoot (144.0, epsilon));
printf ("nsquareRoot (17.5) = %Lfn", squareRoot (17.5, epsilon));
return 0;
}
If you are using the version of Code::Blocks with mingw, see this answer: Conversion specifier of long double in C
mingw ... printf does not support the 'long double' type.
Some more supporting documentation for it.
http://bytes.com/topic/c/answers/135253-printing-long-double-type-via-printf-mingw-g-3-2-3-a
If you went straight from float
to long double
, you may try just using double
instead, which is twice as long as a float to start with, and you may not need to go all the way to a long double
.
For that you would use the print specifier of %lf
, and your loop might want to look something like this, to prevent infinite loops based on your epsilon:
double squareRoot ( double x, double a)
{
double nextGuess = 1.0;
double lastGuess = 0.0;
while ( absoluteValue (nextGuess * nextGuess - x) >= a && nextGuess != lastGuess){
lastGuess = nextGuess;
nextGuess = (x / lastGuess + lastGuess) / 2.0;
printf ("%lfn ", nextGuess);
}
return nextGuess;
}
链接地址: http://www.djcxy.com/p/85736.html
上一篇: 快整数平方根近似
下一篇: 长双的用法