Talk:Kahan summation

Revision as of 10:49, 11 December 2014 by rosettacode>Paddy3118 (→‎Task: Constants)

Task

The idea of showing the Kahan summation on Rosettacode is good, but the Task is not good yet. I suggest to remove the requirements of using a Decimal module and make it optional. So many languages can use normal floating point values. I also suggest to increase the number of input values and the number of their digits, to better show why the Kahan summation is useful.

This is a D version of the Task, without a Decimal:

<lang d>real kahanSum(T)(in T[] data) pure nothrow @safe @nogc {

   real tot = 0, c = 0;
   foreach (immutable x; data) {
       immutable y = x - c;
       immutable t = tot + y;
       c = (t - tot) - y;
       tot = t;
   }
   return tot;

}

void main() {

   import std.stdio, std.algorithm;
   enum a = 10000.0L, b = 3.14159L, c = 2.71828L;
   writefln("%5.10f", (a + b) + c);
   writefln("%5.10f", [a, b, c].kahanSum);
   writefln("%5.10f", [a, b, c].sum);

}</lang>

It prints (the D+Phobos sum performs a Kahan summation):

10005.8598700000
10005.8598700000
10005.8598700000

-bearophile (talk) 10:28, 11 December 2014 (UTC)

Would you need different numbers for different precision numbers? What numbers to choose as I would prefer some standardisation.
Or should it be written so that the example is forced to show the effect with the constants they use? --Paddy3118 (talk) 10:49, 11 December 2014 (UTC)
Return to "Kahan summation" page.