views:

124

answers:

2

As we all know, floating point arithmetic is not always completely accurate, but how do you deal with its inconsistencies?

As an example, in PHP 5.2.9: (this doesn't happen in 5.3)

echo round(14.99225, 4);  // 14.9923 
echo round(15.99225, 4);  // 15.9923 
echo round(16.99225, 4);  // 16.9922 ??
echo round(17.99225, 4);  // 17.9922 ??
echo round(25.99225, 4);  // 25.9922 ??
echo round(26.99225, 4);  // 26.9923

How would you work around this?

+5  A: 

Welcome to IEEE754, enjoy your stay.

Use bc or gmp instead.

Ignacio Vazquez-Abrams
+3  A: 

how do you deal with its inconsistencies?

  • For stuff where exact results based on decimal representation matters (i.e. money), do not use IEEE754 floats, you use "bignum" libraries like BCMath
  • For stuff where you just need your calculations to be relatively precise (like most scientific calculations), you use numerically stable algorithms so that the inconsistencies stay in the least significant bits (where they don't matter).
Michael Borgwardt