<?php
define('EPSILON', 1.0e-8);
function real_cmp($r1, $r2)
{
$diff = $r1 - $r2;
if( abs($diff) < EPSILON )
return 0;
else
return $diff < 0 ? -1 : 1;
}
function real_lt($r1, $r2)
{
return real_cmp($r1, $r2) < 0;
}
echo "raw compare\n";
$n = 0;
for($i = 0.1; $i < 1.0; $i += 0.1) {
$n++;
echo "$i\t$n\n";
}
echo "\nepsilon compare\n";
$n = 0;
for($i = 0.1; real_lt($i, 1.0); $i += 0.1) {
$n++;
echo "$i\t$n\n";
}
?>
So moral of this program? "Never compare floating point numbers for equality" solves only half of the problem. As seen above, even raw comparing of floats for less than (or grater than) is dangerous and epsilon (round, etc.) must be used.