Kahan summation: Difference between revisions

Added XPL0 example.
m (→‎{{header|Wren}}: Changed to Wren S/H)
(Added XPL0 example.)
Line 2,717:
Kahan sum = 1
Delta = 1.1102230246252e-16
</pre>
 
=={{header|XPL0}}==
{{trans|C}}
XPL0's only 'native' floating point type (real) is double-precision, so
the alternative task is performed. The normal output shows no difference
because of rounding, so the hex output is used to show it.
<syntaxhighlight lang "XPL0">include xpllib; \for Print
 
func real KahanSum(Nums, Count);
real Nums; int Count;
real Sum, C, T, Y;
int I;
[Sum:= 0.0;
C:= 0.0;
for I:= 0 to Count-1 do
[Y:= Nums(I) - C;
T:= Sum + Y;
C:= (T - Sum) - Y;
Sum:= T;
];
return Sum;
];
 
func real Epsilon;
real Eps;
[Eps:= 1.0;
while 1.0 + Eps # 1.0 do
Eps:= Eps/2.0;
return Eps;
];
 
real A, B, C, FA(3), D, K;
[A:= 1.0; B:= Epsilon; C:= -B;
FA(0):= A; FA(1):= B; FA(2):= C;
Print("Epsilon = %0.16f\n", B);
D:= (A + B) + C;
Print("(A + B) + C = %0.16f\n", D);
K:= KahanSum(FA, 3);
Print("Kahan sum = %0.16f\n", K);
Print("(A + B) + C = %x %x\n", D);
Print("Kahan sum = %x %x\n", K);
]</syntaxhighlight>
{{out}}
<pre>
Epsilon = 1.1102230246251600E-016
(A + B) + C = 1.0000000000000000E+000
Kahan sum = 1.0000000000000000E+000
(A + B) + C = FFFFFFFF 3FEFFFFF
Kahan sum = 00000000 3FF00000
</pre>
 
297

edits