Jump to content

Kahan summation: Difference between revisions

(Added c#)
Line 194:
{{out}}<pre>Simple: 1.00000E +4 + 3.14159E +0 + 2.71828E +0 = 1.00058E +4
Kahan : 1.00000E +4 + 3.14159E +0 + 2.71828E +0 = 1.00059E +4</pre>
 
=={{header|C++}}==
{{trans|C++}}
<lang cpp>#include <iostream>
 
float epsilon() {
float eps = 1.0f;
while (1.0f + eps != 1.0f) eps /= 2.0f;
return eps;
}
 
float kahanSum(std::initializer_list<float> nums) {
float sum = 0.0f;
float c = 0.0f;
for (auto num : nums) {
float y = num - c;
float t = sum + y;
c = (t - sum) - y;
sum = t;
}
return sum;
}
 
int main() {
using namespace std;
 
float a = 1.f;
float b = epsilon();
float c = -b;
 
cout << "Epsilon = " << b << endl;
cout << "(a + b) + c = " << (a + b) + c << endl;
cout << "Kahan sum = " << kahanSum({ a, b, c }) << endl;
 
return 0;
}</lang>
{{out}}
<pre>Epsilon = 5.96046e-08
(a + b) + c = 1
Kahan sum = 1</pre>
 
=={{header|C#|C sharp}}==
1,452

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.