APM: Perl zero not being zero, but 7e-12
Mike South
msouth at gmail.com
Mon Sep 12 22:59:34 PDT 2005
Floating point numbers are not stored with infinite accuracy, and
subtracitng two of them that look equal (to a print statement) can
bring out the tiny error that actually occurred when they were stored.
A general rule for comparing floating point numbers is to specify a
value that you consider close enough to zero for your purposes, and
check that the absolute value of the difference between the numbers is
less than that value (there's a traditional name for this, maybe
epsilon or some other greek letter used by numerical analysis/compiler
design/computer engineering type people to denote the smallest number
a computer can store).
If you are specifically dealing with money, one thing that business
software will often do it store all values in pennies, so you won't
(as easily) bring in error associated with floating point
representations.
(I'm actually just guessing that this is what you're seeing, of
course--maybe if you can tell us $i and $j and some numerical
representation guru will tell us how those things got converted to
binary or whatever we could confirm it. It's possible that the
problem will come and go depending on whether $i, $j, and the value in
$a are at the boundaries of accurate representability. For example,
if everything involved ended in .50 or .25 (which are representable
exactly in binary) do you see the problem? If that makes it go away
it's probably the problem I'm describing.)
On 9/12/05, David Bluestein II <dbii at interaction.net> wrote:
> Okay, I've seen this before and have a question how to avoid it.
>
> I take two variables:
>
> $a= 38071.63;
> $b = $i + $j; # Where $i + $j => 38071.63
>
> print "$a : $b"; # results in 38071.63 : 38071.63
>
> Yet if I do:
>
> if ($a == $b) {
> print "Equal";
> } else {
> print "Not equal";
> }
>
> I get a "Not equal".
>
> If I subtract ($b-$a) the result is 7.27595761418343e-12. How do I get
> Perl to ignore this "noise" which comes from someplace?
>
> David
>
> -----------------------------------------------------------------------
> David H. Bluestein II
> President & Lead Developer dbii at interaction.net
> ii, inc.
> http://www.interaction.net
> -- Specializing in Interactive, Database Driven Websites --
>
> _______________________________________________
> Austin mailing list
> Austin at pm.org
> http://mail.pm.org/mailman/listinfo/austin
>
More information about the Austin
mailing list