Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd behavior comparing doubles, two PHP double values aren't equivalent

I have two seemingly equal double values in PHP (at least when echoing them).

But when comparing them with double equals, for some reason, it evaluates to false. Are there any special considerations when performing this kind of comparison?

like image 354
Victor Johansson Avatar asked Mar 11 '11 09:03

Victor Johansson


2 Answers

You shouldn't compare floating point numbers using the == operator.

See the big warning and explanation in the php manual

What will work is asserting that the two numbers are within a certain small distance of each other like this:

if(abs($a - $b) < 0.0001) {
    print("a is mostly equal to b");
}

The reason is because of rounding errors due to floating point arithmetic performed after the decimals are converted to binary, then converted back to decimal. These back and forth conversions cause the phenomenon where 0.1 + 0.2 does not equal 0.3.

like image 188
edorian Avatar answered Nov 15 '22 12:11

edorian


float and double should never be compared for equality: there are precision errors that will make two numbers different even if they seem equal (when they are printed out, they are usually rounded).

Proper way to compare is using some DELTA constant:

define(DELTA, 0.00001); // Or whatever precision you require

if (abs($a-$b) < DELTA) {
  // ...
}

Also note that this is not PHP specific but also important in other languages (Java, C, ...)

like image 39
Vincent Mimoun-Prat Avatar answered Nov 15 '22 10:11

Vincent Mimoun-Prat