APM: Perl zero not being zero, but 7e-12
Evan Harris
eharris at puremagic.com
Mon Sep 12 23:05:49 PDT 2005
Doing equality comparisons on floating point numbers is inherently unsafe in
all languages or platforms that don't use arbitrary precision math
libraries, and fraught with danger even in those that do. It is usually
unpredictable between different architectures as well.
The way you should be doing it is decide what your maximum allowed error for
comparisons is, say 1.0e-8, and then comparing if the two numbers are within
your allowed window for "equality", e.g. abs($a - $b) < 1.0e-8.
Evan
On Tue, 13 Sep 2005, HCoyote wrote:
> On Mon, Sep 12, 2005 at 10:46:23AM -0500, David Bluestein II 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?
>
> I suggest a new computer. :-)
>
> I can't get this to do the same thing on any system I test on. Does it happen only one
> one system for you or is it consistently the same number? Does it change depending on
> your choice of $i and $j?
>
>
> Travis
> _______________________________________________
> Austin mailing list
> Austin at pm.org
> http://mail.pm.org/mailman/listinfo/austin
>
More information about the Austin
mailing list