Thursday, November 19, 2009

Float comparison


What's more normal than using '==' or '===' operator to check equality between two numbers ?


That works for most cases, but computers have technical limitations as nobody can represent the exact value of Pi. Binary representation is reliable for integers unless you need to mean an out-of-range value. For decimals and real numbers, you might encounter problem of precision. What's happening with these floating point numbers, also known as floats and doubles (double precision) ?

Example :

$float1 = 1.333;
$float2 = 1.1 + 0.233;

// Are they really equal ?
if ($float1 === $float2)
    echo 'OK';
else
    echo 'ERROR !';

// ERROR !

// Is this a problem of type ?
if (gettype($float1) == gettype($float2))
    echo 'No, $float1 and $float2 are both ' . gettype($float1);
else
    echo 'Yes, $float1 is a ' . gettype($float1) . ' whereas $float2 is a ' . gettype($float2);

// No, $float1 and $float2 are both double

// Where is the problem ?!!
$gap = $float1 - $float2;
echo '$gap = ' . $gap;

Result : $gap = -2.22044604925E-16 !!
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -