[Israel.pm] math problem

Yishay Weiss yishayjobs at hotmail.com
Sun Nov 13 03:50:11 PST 2005


Sounds good to me. BTW, after understanding the problem topic I found it in 
perlfaq4 under:

Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers 
I should be getting (eg, 19.95)?

10x to all who responded,
Yishay

>From: Peter Gordon <peter at pg-consultants.com>
>Reply-To: Perl in Israel <perl at perl.org.il>
>To: Perl in Israel <perl at perl.org.il>
>Subject: Re: [Israel.pm] math problem
>Date: Sun, 13 Nov 2005 13:02:32 +0200
>
>The first rule when using floating point numbers, is never to compare
>them. What you have to do instead is something like this.
>
>$epsilon = 1e-6
>abs($result - $a) < $epsilon
>
>It is up to you to choose the accuracy you need for epsilon.
>
>
>On Sun, 2005-11-13 at 10:43 +0000, Yishay Weiss wrote:
> > Hi,
> >
> > This here is so basic I can't imagine it wasn't discussed before. Still,
> > does anyone care to tell me what's going on here? Can perl be failing to
> > subtract properly?
> >
> > I run this script: (perl 5.8.4 on windows XP, but I also tried it with 
>5.8.0
> > on Linux)
> >
> > ========
> >
> > $a = 0.3847;
> > $b = 0.4303;
> > $c = 0.0456;
> >
> > $result = $b - $c;
> >
> > print "a: $a\nresult: $result\n";
> > print "a == result ? ". ($a == $result)."\n";
> >
> > =====
> >
> > and I get:
> >
> > =====
> >
> > a: 0.3847
> > result: 0.3847
> > a == result ?
> >
> > =======
> >
> > Which is wrong. Then I run the same script with slightly bigger numbers:
> >
> > ========
> >
> > $a = 0.3847 * 10;
> > $b = 0.4303 * 10;
> > $c = 0.0456 * 10;
> >
> > $result = $b - $c;
> >
> > print "a: $a\nresult: $result\n";
> > print "a == result ? ". ($a == $result)."\n";
> >
> > =========
> >
> > and get:
> >
> > ========
> >
> > a: 3.847
> > result: 3.847
> > a == result ? 1
> >
> > =======
> >
> > Which makes perfect sense. Any ideas?
> >
> > Yishay
> >
> >
> > _______________________________________________
> > Perl mailing list
> > Perl at perl.org.il
> > http://perl.org.il/mailman/listinfo/perl
> >
> >
>
>
>_______________________________________________
>Perl mailing list
>Perl at perl.org.il
>http://perl.org.il/mailman/listinfo/perl





More information about the Perl mailing list