[Detroit-pm] Strange problem with simple math in perl

Jonathan Billings billings at negate.org
Thu Nov 12 09:33:10 PST 2009


On Thu, Nov 12, 2009 at 10:34:35AM -0500, Jim McQuillan wrote:
> The result I get is:
> 
>    new_bal: 7.105427357601e-15
> 
> That's awfully close to the right answer, but I'm depending on perl
> to be useful for calculating account balances.

A couple people suggested using printf() or sprintf(), however
perlfaq4 says:

       Rounding in financial applications can have serious
       implications, and the rounding method used should be
       specified precisely.  In these cases, it probably pays
       not to trust whichever system rounding is being used by
       Perl, but to instead implement the rounding function you
       need yourself.

       To see why, notice how you'll still have an issue on
       half-way-point alternation:

           for ($i = 0; $i < 1.01; $i += 0.05) { printf "%.1f ",$i}

           0.0 0.1 0.1 0.2 0.2 0.2 0.3 0.3 0.4 0.4 0.5 0.5 0.6 0.7 0.7
           0.8 0.8 0.9 0.9 1.0 1.0

       Don't blame Perl.  It's the same as in C.  IEEE says we
       have to do this.  Perl numbers whose absolute values are
       integers under 2**31 (on 32 bit machines) will work
       pretty much like mathematical integers.  Other numbers
       are not guaranteed.


-- 
Jonathan Billings <billings at negate.org>


More information about the Detroit-pm mailing list