On 9/1/10 Wed Sep 1, 2010 1:46 PM, "Jim" <j...@lowcarbfriends.com> scribbled:
> 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? I don't worry about it. I do the calculations and print out the result with printf to whatever precision I need and what I feel is warranted by the accuracy of the input data. Double-precision 64-bit floating-point has ALWAYS been accurate enough for my needs. If I happen to print out some intermediate results, I don't worry about such "errors" as you have shown, since I know they are normal for computer-based arithmetic. In real life, an arithmetic evaluation never results in a value that will print as "-0.00". And if it did, it wouldn't bother me. It is still zero to two places. One good approach: plot your data rather than printing it, if possible. It is easier to see patterns, averages, outliers, etc. in a plot than it is in a list of numbers. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/