0

I am new to PHP and trying to perform a simple arithmetic addition and comparison. I have an array with some decimal values and after adding all the values, I am trying to compare it to 1. My array is:

$myArray=[0.2,0.7,0.1] 

and my code is:

$sum=0;
foreach($myArray as $val){
    $sum+=$val;             
}

Here, the sum comes out to be 1. But when I compare it using the following code:

if($sum!=1)
{
    echo "Good";
}
else
{
    echo "Bad";
}

it echoes "Good".

However, when my array contains values 0.8 and 0.2, it echoes "Bad". Can anyone help me on this?

geoff
  • 2,251
  • 1
  • 19
  • 34
AppleBud
  • 1,501
  • 8
  • 31
  • 47

1 Answers1

3

If you check the PHP docs on floating-point numbers: php.net/manual/en/language.types.float.php, there is a huge warning on the page.

"Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and, of course, error propagation must be considered when several operations are compounded."

Thus, you could get unexpected results such as 0.2 + 0.7 = 0.900000000001. It's simply because computers have a hard time representing decimals. Binary was really built for integers.

Careful in your logic; I think you meant if($sum == 1) echo "Good", etc. In that case, 0.2+0.7+0.1 would echo "Bad", because it's totally possible that 0.2+0.7+0.1 = 1.00000001 or 0.99999999. On the other hand, adding a smaller number of floats together decreases the error, so 0.8+0.2 is more precise than 0.2+0.7+0.1.

geoff
  • 2,251
  • 1
  • 19
  • 34