Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix this problem in PHP?

$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?

like image 360
user198729 Avatar asked Jan 03 '10 15:01

user198729


2 Answers

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
like image 117
Ignacio Vazquez-Abrams Avatar answered Oct 15 '22 21:10

Ignacio Vazquez-Abrams


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.

like image 39
mjv Avatar answered Oct 15 '22 23:10

mjv