On Thu, Sep 2, 2010 at 09:32, Jim <j...@lowcarbfriends.com> wrote:
snip
> It's really not a question of it being perplexing more so than like I said
> maddening in terms of why solutions just aren't intrinsic to the programming
> language. If ops are slower, so what... throw some more hw at the problem...
> hw is cheap... people's time isn't.
snip

The idea that hardware is cheap and people's time is expensive is a
relatively new idea.  For most of computing history, CPU time has been
more valuable than a human's time.  And the idea that human time is
more important than CPU time will only last so long as Moore's Law
holds out and we have cheap power sources.

> I was hoping I'd see some answer like... oh yeah... perl is smart enough to
> handle that for you if you are willing to accept a performance hit... just
> turn on so-and-so directive and perl will perform in non-floating point mode
> and return precise answers up to some level of precision... just like your
> calculator. I undertand there are modules that will help, but it sounds like
> those involve significant coding changes. Or like others suggest, convert
> everything to cents or fractions of cents and then divide at the end...
> requires a lot of foresight or backtracking.

There are pragmas that transparently use higher precision and accuracy
libraries for you in the Perl 5 core: take a look at [bigint][0],
[bignum][1], and [bigrat][2], but there is a performance hit.  Using
bignum with your original code outputs:

total = 0
total = 21835.3
total = 119.4
total = 9771.6
total = 0
total = 0.00

#!/usr/bin/perl

use strict;
use warnings;

use bignum;

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");

 [0]: http://perldoc.perl.org/bigint.html
 [1]: http://perldoc.perl.org/bignum.html
 [2]: http://perldoc.perl.org/bigrat.html

-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to