Jump to content

[SOLVED] php cannot recognize that 2.0 - 1.9 = 0.1 ?


johnny44

Recommended Posts

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?

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

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.

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";

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.