Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gcc precision bug?

Tags:

gcc

precision

I can only assume this is a bug. The first assert passes while the second fails:

double sum_1 =  4.0 + 6.3;
assert(sum_1 == 4.0 + 6.3);

double t1 = 4.0, t2 = 6.3;

double sum_2 =  t1 + t2;
assert(sum_2 == t1 + t2);

If not a bug, why?

like image 970
Jesse Elliott Avatar asked Aug 26 '09 23:08

Jesse Elliott


1 Answers

You are comparing floating point numbers. Don't do that, floating point numbers have inherent precision error in some circumstances. Instead, take the absolute value of the difference of the two values and assert that the value is less than some small number (epsilon).

void CompareFloats( double d1, double d2, double epsilon )
{
    assert( abs( d1 - d2 ) < epsilon );
} 

This has nothing to do with the compiler and everything to do with the way floating point numbers are implemented. here is the IEEE spec:

http://www.eecs.berkeley.edu/~wkahan/ieee754status/IEEE754.PDF

like image 139
Ed S. Avatar answered Sep 23 '22 02:09

Ed S.