php - Trying to compare a calculation on float values returns false -
this question has answer here:
- how floating point stored? when matter? 10 answers
why equals allways false?
<?php $a = (0.1+0.2); print $a."\n"; // results in 0.3 if ( (double)$a == (double)0.3 ) { echo "true"; }else{ echo "not true"; } echo php_eol;
perl
perl -e 'if ((0.2+0.1) == 0.3) {print "true\n"; } else { print "false\n"; }'
and in python
python -c 'if ((0.2+0.1)!=0.3 ): print "false" '
you need specify tolerance [also referred epsilon] when comparing floating point values since it not exact representation of number.
function f_cmp(float $a, float $b, float $tol = 0.00001) { if( abs($a - $b) < $tol ) { return 0; } else { return $a - $b; } // return 0 if "equal" within tolerance // return < 0 if $a < $b // return > 0 if $a > $b // use php functions usort() }
or simply:
function f_eq(float $a, float $b, float $tol = 0.00001) { if( abs($a - $b) < $tol ) { return true; } else { return false; } }
Comments
Post a Comment