81.4 is evil

I know many of you all know pretty well that floating point precision and computers don’t play nicely with each other. I think I learned about it in the first book on ‘C’ I ever read, but I had never really been bitten by it until today. I was working with a piece of code today at the office that was throwing an error saying two values weren’t zeroing out when they clearly should have been. I narrowed down the problem and after a bit of time decided that 81.4 is a terrible, terrible number. For example:

So, let that be a lesson to us all. No matter how simple the calculation, don’t blindly trust floats.

7 thoughts on “81.4 is evil”

  1. As any other guy I knew about floating point precision, but I always thought that it could only lose precision in the least significant digits, numerous digits after the decimal point and that it would only happen in inextricably complicated and rare situations. Now that I’ve run your very small and simple snippet I’m blown off.

    Thanks for sharing that insightful piece of information, now you’ve increased my paranoia by at least 7.105427357601E15 percents 😉

  2. use the bcmath library : [url]http://www.php.net/manual/en/ref.bc.php[/url]

    [geshi lang=php]
    $truetotal = (float) bcadd(‘100’, ‘-81.4’, 1);

    echo “18.6 == {$truetotal}? ” .
    ($truetotal === 18.6 ? ‘yes’ : ‘no’) .
    “n”;

    var_dump(18.6 – $truetotal);
    [/geshi]
    output => 18.6 == 18.6? yes

Leave a Reply

Your email address will not be published. Required fields are marked *