johnny44 Posted March 4, 2008 Share Posted March 4, 2008 Php apparently cannot recognize that 2.0-1.9 = 0.1. When I run the following code ... <? $A=2.0-1.9; if($A==0.1) { echo "Correct"; } else { echo "Php cannot recognize that 2.0-1.9 = 0.1"; } ?> ... it returns "Php cannot recognize ...". If I then ask php to output what it thinks the difference between (2.0-1.9) and 0.1 is, it says: 8.32667268469E-017 I realize there can be decimal errors for complex calculations but php can go wrong with even such a simple calculation? I'm running a simple statistics web-based program using php and discovered this. Am I doing anything wrong or is the fault solely with php? Quote Link to comment Share on other sites More sharing options...
PFMaBiSmAd Posted March 4, 2008 Share Posted March 4, 2008 This is actually a computer/binary math problem. Not just a php problem. Because floating point numbers have finite precision, any conversion into/out of a floating point binary representation in a computer results in loss of precision. To do what you want without the errors due to just converting into/out of floating point, use the BC (BCD) math extension - http://www.php.net/manual/en/ref.bc.php Quote Link to comment Share on other sites More sharing options...
fnairb Posted March 4, 2008 Share Posted March 4, 2008 The evil of floating point numbers. See the warning on http://us.php.net/float for how to deal with them. Quote Link to comment Share on other sites More sharing options...
johnny44 Posted March 4, 2008 Author Share Posted March 4, 2008 Thank you guys. I forgot to think in binary. A remark within one of your links pointed out that 0.1 expressed in binary does not terminate, and so cannot be accurately represented in a finite register. I think I understand. I thought that with the "exact" numbers 2.0 and 0.1, there would be no problem. Quote Link to comment Share on other sites More sharing options...
deadonarrival Posted March 7, 2008 Share Posted March 7, 2008 I think you're okay if the numbers are both exact powers of 2, but otherwise it does its own thing. Quote Link to comment Share on other sites More sharing options...
Barand Posted March 7, 2008 Share Posted March 7, 2008 Basically it's a case of deciding that if two fp numbers differ by say, 0.000001, then tat is near enough for them to be considered equal. So in the above example, $A = 2.0 - 1.9; if (abs($A - 0.1) < 0.000001) { echo "Equal"; } This works as the fractional bits are powers of 1/2 <?php $a = 2.5 - 2.25; if ($a == 0.25) echo "Equal"; ?> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.