$onethird = 1.0/3;
$fivethirds = 1.0/3+1.0/3+1.0/3+1.0/3+1.0/3;
$half = 1.0/2;
$threehalf = 1.0/2+1.0/2+1.0/2;
var_dump($onethird + $fivethirds == $half + $threehalf);
which outputs false
,but as we all know:5/3+1/3=2=3/2+1/2
How to fix this problem?
This is one of the problems with the IEEE 754 representation of floating point numbers; the representations are not accurate enough to represent all rational numbers.
The way to do it is to compare the difference against a very small number for closeness, rather than equality:
abs(($onethird + $fivethirds) - ($half + $threehalf)) < 1e-8
The problem comes from the small errors introduced by Floating Point arithmetic. This is not specific to PHP.
You can fix this by introducing a small "tolerance" factor, i.e. by checking that the first value in the comparaision is >= the second value minus the tolerance and <= the second value plus the tolerance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With