I personally prefer relative precision, rather than absolute values, as you frequently don't know what the scale of the number is going to be for these sorts of calculations:
sub fp_equal { my ($x,$y,$precision) = @_; $precision ||= 0.000001; return 1 if (! defined($x) and ! defined($y) ); return 0 if (! defined($x) or ! defined($y) ); return 1 if ($x == $y); # for 0 == 0 ($x,$y) = ($y,$x) if (!$y); # for $y == 0 return ( abs ( 1 - $x/$y ) <= $precision ) ? 1 : 0; }
Update: I made an assumption based on the halving of the precision in the OP's problem that this was doing some sort of numerical analysis. ikegami is right in that sometimes you're looking at stepped measurements over a finite range, and so an absolute precision is necessary. (Most of my floating point comparisons are in scientific measurements, and I use relative precision so I don't have to have different definitions of precision for the units used and range of the measurements)
In reply to Re^3: Infinite loop but no reason why
by jhourcle
in thread Infinite loop but no reason why
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |