Subject: | add sumc() (Kahan) |
Date: | Tue, 31 Dec 2019 14:05:40 +0100 |
To: | bug-List-MoreUtils [...] rt.cpan.org |
From: | "Ruud H.G. van Tol" <rvtol [...] isolution.nl> |
sub sumc {
# Compensate for loss of precision.
# See https://en.wikipedia.org/wiki/Kahan_summation_algorithm
my ($sum, $corr)= (shift, 0);
for my $v ( @_ ) {
my $sum_next= $sum + $v;
$corr+= ( abs($sum) >= abs($v) )
? (($sum - $sum_next) + $v)
: (($v - $sum_next) + $sum);
$sum= $sum_next;
}
return $sum + $corr;
}
$ perl -Mstrict -MList::Util=sum -wE'
sub sumc { ... }
my @values= (1, 1e100, 1, -1e100);
say for sum(@values), sumc(@values);
'
0
2
-- Greetings, Ruud