[grand-rapids-pm-list] Second grade math is giving me problems
grand-rapids-pm-list at pm.org
grand-rapids-pm-list at pm.org
Tue Mar 10 08:18:47 PDT 2009
Hi all,
I'm working with bit of code that is so basic and so simple that
perhaps I can't see the easy explanation as to why I am not getting
the expected output. I'm really baffled here.
It simply adds or subtracts numbers from a account balance based on
whether it is a deposit or withdraw. Simple enough, right? Well, i
guess not for me...
Here is the code:
my @summary = ();
$summary[0] = [ 1, 444.01 ];
$summary[1] = [ 2, 366.41 ];
$summary[2] = [ 1, 62.03 ];
$summary[3] = [ 2, 77.60 ];
$summary[4] = [ 1, 7.23 ];
$summary[5] = [ 2, 66.03 ];
$summary[6] = [ 1, 71.65 ];
$summary[7] = [ 2, 74.88 ];
my $balance = 0;
foreach my $line (@summary) {
my ($method, $amount) = @{$line};
print "Cur Balance: $balance ";
if ($method == 1) {
$balance = $balance + $amount;
} elsif ($method == 2) {
$balance = $balance - $amount;
}
print "New Balance: $balance\n";
}
As you can likely determine, the @summary variable is an array of
arrays; the later of which holds two values. The first value being 1
or 2. 1 for a deposit and 2 for a withdrawal. The second value being
the amount in question.
With an account balance starting at zero, evaluating these numbers
should result in an ending balance of zero i.e. the total deposits are
equal to the total withdrawals. However, while looping over the array,
I'm getting funny results like long decimal values and a final balance
of -1.42.
Here is the output i'm seeing:
Cur Balance: 0 New Balance: 444.01
Cur Balance: 444.01 New Balance: 77.6
Cur Balance: 77.6 New Balance: 139.63
Cur Balance: 139.63 New Balance: 62.03
Cur Balance: 62.03 New Balance: 69.26
Cur Balance: 69.26 New Balance: 3.22999999999998
Cur Balance: 3.22999999999998 New Balance: 74.88
Cur Balance: 74.88 New Balance: -1.4210854715202e-14
I suspect running this code through your perl interpreter would give
you the same results. I'm convinced the problem is something simple,
but I just don't see it. Anyone have any ideas?
- Brian
More information about the grand-rapids-pm-list
mailing list