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

Fred Posner fred at teamforrest.com
Thu Nov 12 07:46:34 PST 2009


What about with sprintf?

#!/usr/bin/perl -w

use strict;

my $new_bal = (123.00-69.63-53.37);
$new_bal = sprintf("%.2f", $new_bal);
print("new_bal: $new_bal\n");



---fred
http://qxork.com







On Nov 12, 2009, at 10:43 AM, Joe Landman wrote:

> 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
> _______________________________________________
> Detroit-pm mailing list
> Detroit-pm at pm.org
> http://mail.pm.org/mailman/listinfo/detroit-pm



More information about the Detroit-pm mailing list