Accuracy of math.h functions

27 Dec 2011

Dear all,

I'm using the math function sqrt from math.h with long double variables and found out, that mbed calculated sqrt(2) = 1,41421354 (C-codeline is: "x = (long double) sqrt((float)x);" where x is defined as long double). I inserted the type conversions due to the fact that sqrt is defined as float according to the C book I'm using (Herbert Schildt "C++ from the ground up"). If you insert the result into the formula 1,41421354 * 1,41421354 you'll get 1,99999993 as result. I used lcd.printf ("%# 1.8Lf,x); for the output. Using "%# 1.10Lf" as format string wasn't that much better. The HP Smartcalc 300 calculates sqrt(2) = 1,414213562 and 1,414213562 * 1,414213562 = 2,000000000.

Am I making a mistake here or is there an alternative math library with higher accuracy ?

Thanks for any hint in advance.

Regards

Karl

27 Dec 2011

According to http://www.cplusplus.com/reference/clibrary/cmath/sqrt/

the sqrt() is available for float, double and long double:

double sqrt (double x ); float sqrt (float x ); long double sqrt (long double x );

try out

long double x;
x = (long double) 2.0;
printf ("%ld", sqrt(x) * sqrt(x)); 
29 Dec 2011

Hi Wim,

thank you very much for your reply. Deleting the unecessary type casts did the trick. And thanks for the link, too.

Regards

Karl