[Israel.pm] math problem
Peter Gordon
peter at pg-consultants.com
Sun Nov 13 03:02:32 PST 2005
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
>
>
More information about the Perl
mailing list