Simple math failing - PHP Bug?
| From: | Brian T. Allen | Date: | Mon, 01 Nov 2004 04:52:32 +0000 |
| Subject: | Simple math failing - PHP Bug? | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-200804@lists.php.net to get a copy of this message | ||
Hi,
OK, I'm totally stumped by this. This should be the simplest math imaginable (addition and subtraction), but PHP is coming up with the wrong answer!
I've checked on 3 different machines (all linux) running both PHP 4 and PHP 5.
Here is the code to duplicate the problem:
-----------------------------------
<?php
$a = 2503.54;
$b = 303.55;
$c = 202.13;
$total = 0;
$total += $a;
$total += $b;
$total += $c;
$added_total = $total;
echo "$a + $b + $c = $total<br>";
echo "Actual: $total<br><br>";
$total -= $a;
$total -= $b;
$total -= $c;
echo "$added_total - $a - $b - $c = 0<br>";
echo "Actual: $total<br><br>";
?>
-----------------------------------
This ~should~ output this:
2503.54 + 303.55 + 202.13 = 3009.22
Actual: 3009.22
3009.22 - 2503.54 - 303.55 - 202.13 = 0
Actual: 0
But instead it outputs this:
2503.54 + 303.55 + 202.13 = 3009.22
Actual: 3009.22
3009.22 - 2503.54 - 303.55 - 202.13 = 0
Actual: 2.84217094304E-13
Now I'm the first to admit that 0.000000000000284217094304 and 0 are really very close, but when you are testing a variable to see if it equals 0, it is the difference between true and false.
This seems very, very basic to me, but I can't find the flaw in my code.
Is this legitimately bad math on the part of PHP?
Thanks,
Brian