Kahan summation: Difference between revisions

→‎{{header|Perl 6}}: Add Perl 6 example
m (added whitespace to the task's preamble.)
(→‎{{header|Perl 6}}: Add Perl 6 example)
Line 1,037:
{{out}}
<pre>%1 = 1.000000000000000000</pre>
 
=={{header|Perl 6}}==
{{trans|Python}}
Perl&nbsp;6 does not offer a fixed precision decimal. It does have does have IEEE 754 floating point numbers so let's try implementing the arbitrary precision option as shown in Python. Need to explicitly specify scientific notation numbers to force floating point Nums.
 
<lang perl6>constant ε = (1e0, */2e0 … *+1e0==1e0)[*-1];
 
sub kahan (*@nums) {
my $summ = my $c = 0e0;
for @nums -> $num {
my $y = $num - $c;
my $t = $summ + $y;
$c = ($t - $summ) - $y;
$summ = $t;
}
$summ
}
 
say 'Epsilon: ', ε;
 
say 'Simple sum: ', ((1e0 + ε) - ε).fmt: "%.16f";
 
say 'Kahan sum: ', kahan(1e0, ε, -ε).fmt: "%.16f";</lang>
{{out}}
<pre>Epsilon: 1.1102230246251565e-16
Simple sum: 0.9999999999999999
Kahan sum: 1.0000000000000000
</pre>
 
=={{header|PHP}}==
10,333

edits