:

## add, floats, and Kahan sum

Maple

add, floats, and Kahan sum

I found an intresting fact about the Maple command add for floating point values.
It seems that add in this case uses a summation algorithm in order to reduce the numerical error.
It is probably the Kahan summation algorithm (see wiki), but I wonder why this fact is not documented.

Here is a simple Maple procedure describing and implementing the algorithm.

 > restart;
 > Digits:=15;
 (1)
 > KahanSum := proc(f::procedure, ab::range)   local S,c,y,t, i;      # https://en.wikipedia.org/wiki/Kahan_summation_algorithm S := 0.0;              # S = result (final sum: add(f(n), n=a..b)) c := 0.0;              # c = compensation for lost low-order bits. for i from lhs(ab) to rhs(ab) do     y := f(i) - c;          t := S + y;                   c := (t - S) - y;             S := t;                   od;                          return S end proc:

Now, a numerical example.

 > f:= n ->  evalf(1/(n+1/n^3+1) - 1/(n+1+1/(n+1)^3+1));
 (2)
 > n := 50000; K := KahanSum(f, 1..n);
 (3)
 > A := add(f(k),k=1..n);
 (4)
 > s:=0.0:  for i to n do s:=s+f(i) od: 's' = s;
 (5)
 > exact:=( 1/3 - 1/(n+1+1/(n+1)^3+1) );
 (6)
 > evalf( [errK = K-exact, errA = A-exact, err_for=s-exact] );
 (7)
 > evalf[20]( [errK = K-exact, errA = A-exact, err_for=s-exact] );
 (8)
 >

﻿