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?

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.