Can anyone comment how they handle floating point precision situations
like this?
Here is a basic toy program:
#!/usr/bin/perl
use strict;
my $total = 0;
my $a = 21835.30;
my $b = -21715.90;
my $c = 9652.20;
my $d = -9771.60;
print ("total = $total\n");
$total += $a;
print ("total = $total\n");
$total += $b;
print ("total = $total\n");
$total += $c;
print ("total = $total\n");
$total += $d;
print ("total = $total\n");
$total = sprintf("%.2f", $total);
print ("total = $total\n");
And here is the output:
total = 0
total = 21835.3
total = 119.399999999998
total = 9771.6
total = -1.81898940354586e-12
total = -0.00
Note the lack of precision adding these simple numbers which do not have
a large number of digits to the right of the decimal.
If the line:
$total = sprintf("%.2f", $total);
would produce 0.00 rather than -0.00 I could live with this.
But the only solution I have to get the final answer to properly be 0.00
is to format
$total = sprintf("%.2f", $total);
after each increment is added to $total
or maybe put a string comparison at the end checking for "-0.00" and
changing it to "0.00" if it matches.
I don't like either of these solutions.
How do others deal with this?
Thanks,
Jim
--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/