Subtraction weirdness
Posted: Wed Dec 14, 2011 11:32 am
I know this is due to floating point math fun, but I'm curious why we have never run into this before.
Expected:
10.88 27
7.99 2.89
0 7.99
Actual:
10.88 27
7.99 2.89
1.776356839E-15 7.99
My company has been running PHP since the /FI days, and I'm certain we've had similar code to this. I've never seen this result before. I've tried a few different combinations, and this one seems 100% repeatable on our system, while similar code returns the "correct" response.
This honestly scares me a bit as I know in our large codebase there are probably similar cases. What is it about this specific code that triggers this behavior so I can track down similar places?
Thanks!
Code: Select all
<?
$total = 27+2.89+7.99;
$amounts[] = 27;
$amounts[] = 2.89;
$amounts[] = 7.99;
foreach ($amounts as $key => $value) {
$total -= $value;
echo "$total $value\n";
}
?>10.88 27
7.99 2.89
0 7.99
Actual:
10.88 27
7.99 2.89
1.776356839E-15 7.99
My company has been running PHP since the /FI days, and I'm certain we've had similar code to this. I've never seen this result before. I've tried a few different combinations, and this one seems 100% repeatable on our system, while similar code returns the "correct" response.
This honestly scares me a bit as I know in our large codebase there are probably similar cases. What is it about this specific code that triggers this behavior so I can track down similar places?
Thanks!