Kahan summation: Difference between revisions

(Add Rust implementation)
Line 1,420:
(a + b) + c = 1.00000000
Kahan sum = 1.00000000</pre>
 
=={{header|Nim}}==
In version 1.4.x, Nim doesn’t provide decimal point arithmetic. So we use floating points with the alternative task.
 
The standard module <code>std/sums</code> contains the procedure <code>sumKbn</code> which uses the Kahan-Babuška-Neumaier algorithm, an improvement of Kahan algorithm. So, we compute the sum of 1.0, epsilon and -epsilon using a translation of Kahan algorithm as described in Wikipedia article and also using <code>sumKbn</code>. As expected, in this simple case there is no difference between these algorithms, but in other cases, results may differ.
 
<lang Nim>import std/sums
 
# "std/sums" proposes the "sumKbn" function which uses the
# Kahan-Babuška-Neumaier algorithm, an improvement of Kahan algorithm.
 
func kahanSum[T](input: openArray[T]): T =
var c = T(0)
for val in input:
let y = val - c
let t = result + y
c = (t - result) - y
result = t
 
template isOne[T](n: T): string =
if n == 1: "yes" else: "no"
 
var epsilon = 1.0
while 1 + epsilon != 1:
epsilon = epsilon / 2
 
let a = 1.0
let b = epsilon
let c = -epsilon
 
echo "Computing sum of 1.0, epsilon and -epsilon for epsilon = ", epsilon, '.'
echo "Is result equal to 1.0?"
echo "- simple addition: ", (a + b + c).isOne
echo "- using Kahan sum: ", kahanSum([a, b, c]).isOne
echo "- using stdlib: ", sumKbn([a, b, c]).isOne</lang>
 
{{out}}
<pre>Computing sum of 1.0, epsilon and -epsilon for epsilon = 1.110223024625157e-16.
Is result equal to 1.0?
- simple addition: no
- using Kahan sum: yes
- using stdlib: yes</pre>
 
=={{header|Objeck}}==
Anonymous user