// KahanSum: the sum of a list of FLOAT values by compensated summation // (Kahan, 1965). C holds the low-order part the last addition lost, and the // next addition puts it back, so the error bound, about twice the unit // roundoff times the sum of the absolute values (Higham, section 4.3), does // not grow with the length of the list, to first order. It is relative to // that sum of absolute values, not to the result: KahanSum([1.0e100, 1.0, // -1.0e100]) is 0.0. In exact arithmetic C is always 0 and this is the // plain sum: the compensation exists only because of rounding. A compiler // allowed to reorder FLOAT arithmetic (-ffast-math) can simplify C away. FUNCTION KahanSum(X : LIST OF FLOAT) RETURNS FLOAT DECLARE Total : FLOAT <- 0.0 DECLARE C : FLOAT <- 0.0 FOR I <- 0 TO LENGTH(X) DECLARE Y : FLOAT <- X[I] - C DECLARE T : FLOAT <- Total + Y C <- (T - Total) - Y Total <- T NEXT I RETURN Total ENDFUNCTION