Topics

Numbers

Test for equality of floating point numbers carefully.

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

    print "---\n";
    print "A: ", 2.4, "\n";
    print "B: ", 0.2*12, "\n";
    if ( 0.2*12 == 2.4 ) {
        print "These are equal.\n";
    }
    else {
        print "These are not equal.\n";
    }

    A: 2.4
    B: 2.4
    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.


We want your feedback

If we can improve perl101.org in any way, please let us know with this form.

Your name
Your email
Your comment