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

Joe Landman landman at scalableinformatics.com
Thu Nov 12 07:43:41 PST 2009


Jim McQuillan wrote:
> Hey guys,
> 
> I'm having an issue with doing simple arithmetic in perl.
> 
> I suspect it's a floating-point issue.
> 
> here's the code:

[...]

> 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.

Remember that Perl uses FP representations of your numbers, and while 
123.0 may have an exact FP representation in the limited number of 
mantissa bits (52 for double precision), 69.63 amd 53.37 may not be 
"accurately" represented, to infinite precision, within these 52 bits.

So you are seeing an example of finite precision of the FP 
representation reflected in your example.  What you likely need is to 
either truncate numbers below $0.01, or round them.

Lots of wall street types used fixed precision rather than FP  just for 
this reason.

To get to your problem, I'd suggest doing something like

	my $tmp	= $ans*100.0;
	my $tmp2= int(0.5+$tmp);
	$ans	= $tmp2/100.0;

to lop off the digits below 1 cent in a "meaningful" manner.  This 
implements a rounding operation via INT, but you could do other things 
as well.

Joe


-- 
Joseph Landman, Ph.D
Founder and CEO
Scalable Informatics Inc.
email: landman at scalableinformatics.com
web  : http://scalableinformatics.com
        http://scalableinformatics.com/jackrabbit
phone: +1 734 786 8423 x121
fax  : +1 866 888 3112
cell : +1 734 612 4615


More information about the Detroit-pm mailing list