Numbers

Test for equality of floating point numbers carefully.

IEEE floating point numbers are wrongly over-trusted in calculations.Observe:

  1. print "---\n";
  2. print "A: ", 2.4, "\n";
  3. print "B: ", 0.2*12, "\n";
  4. if ( 0.2*12 == 2.4 ) {
  5. print "These are equal.\n";
  6. }
  7. else {
  8. print "These are not equal.\n";
  9. }
  10.  
  11. A: 2.4
  12. B: 2.4
  13. These are not equal.

This is the result of the fact that 0.2 ( 1/5 ) cannot be represented as a binary fraction in IEEE space.

Thus, if you're checking floating-point equality, use sprintf or similar.

See http://perldoc.perl.org/perlfaq4.html for details.


Want to contribute?

Submit a PR to github.com/petdance/perl101