Kahan Summation Algorithm

Get Kahan Summation Algorithm essential facts below. View Videos or join the Kahan Summation Algorithm discussion. Add Kahan Summation Algorithm to your PopFlock.com topic list for future reference or share this resource on social media.
## The algorithm

### Worked example

## Accuracy

## Further enhancements

## Alternatives

## Possible invalidation by compiler optimization

## Support by libraries

## See also

## References

## External links

This article uses material from the Wikipedia page available here. It is released under the Creative Commons Attribution-Share-Alike License 3.0.

Kahan Summation Algorithm

In numerical analysis, the **Kahan summation algorithm**, also known as **compensated summation**,^{[1]} significantly reduces the numerical error in the total obtained by adding a sequence of finite-precision floating-point numbers, compared to the obvious approach. This is done by keeping a separate *running compensation* (a variable to accumulate small errors).

In particular, simply summing *n* numbers in sequence has a worst-case error that grows proportional to *n*, and a root mean square error that grows as for random inputs (the roundoff errors form a random walk).^{[2]} With compensated summation, the worst-case error bound is effectively independent of *n*, so a large number of values can be summed with an error that only depends on the floating-point precision.^{[2]}

The algorithm is attributed to William Kahan.^{[3]} Similar, earlier techniques are, for example, Bresenham's line algorithm, keeping track of the accumulated error in integer operations (although first documented around the same time^{[4]}) and the delta-sigma modulation^{[5]}

In pseudocode, the algorithm will be;

functionKahanSum(input)varsum = 0.0 // Prepare the accumulator.varc = 0.0 // A running compensation for lost low-order bits.fori = 1toinput.lengthdo// The arrayinputhas elements indexed input[1] to input[input.length].vary = input[i] - c //cis zero the first time around.vart = sum + y // Alas,sumis big,ysmall, so low-order digits ofyare lost. c = (t - sum) - y //(t - sum)cancels the high-order part ofy; subtractingyrecovers negative (low part ofy) sum = t // Algebraically,cshould always be zero. Beware overly-aggressive optimizing compilers!nexti // Next time around, the lost low part will be added toyin a fresh attempt.returnsum

This example will be given in decimal. Computers typically use binary arithmetic, but the principle being illustrated is the same. Suppose we are using six-digit decimal floating-point arithmetic, `sum`

has attained the value 10000.0, and the next two values of `input[i]`

are 3.14159 and 2.71828. The exact result is 10005.85987, which rounds to 10005.9. With a plain summation, each incoming value would be aligned with `sum`

, and many low-order digits would be lost (by truncation or rounding). The first result, after rounding, would be 10003.1. The second result would be 10005.81828 before rounding and 10005.8 after rounding. This is not correct.

However, with compensated summation, we get the correct rounded result of 10005.9.

Assume that `c`

has the initial value zero.

y = 3.14159 - 0.00000y = input[i] - ct = 10000.0 + 3.14159 = 10003.14159 But only six digits are retained. = 10003.1 Many digits have been lost! c = (10003.1 - 10000.0) - 3.14159 Thismustbe evaluated as written! = 3.10000 - 3.14159 The assimilated part ofyrecovered, vs. the original fully. = -0.0415900 Trailing zeros shown because this is six-digit arithmetic. sum = 10003.1 Thus, few digits frominput(i) met those ofsum.

The sum is so large that only the high-order digits of the input numbers are being accumulated. But on the next step, `c`

gives the error.

y = 2.71828 - (-0.0415900) The shortfall from the previous stage gets included. = 2.75987 It is of a size similar toy: most digits meet. t = 10003.1 + 2.75987 But few meet the digits ofsum. = 10005.85987 And the result is rounded = 10005.9 To six digits. c = (10005.9 - 10003.1) - 2.75987 This extracts whatever went in. = 2.80000 - 2.75987 In this case, too much. = 0.040130 But no matter, the excess would be subtracted off next time. sum = 10005.9 Exact result is 10005.85987, this is correctly rounded to 6 digits.

So the summation is performed with two accumulators: `sum`

holds the sum, and `c`

accumulates the parts not assimilated into `sum`

, to nudge the low-order part of `sum`

the next time around. Thus the summation proceeds with "guard digits" in `c`

, which is better than not having any, but is not as good as performing the calculations with double the precision of the input. However, simply increasing the precision of the calculations is not practical in general; if `input`

is already in double precision, few systems supply quadruple precision, and if they did, `input`

could then be in quadruple precision.

A careful analysis of the errors in compensated summation is needed to appreciate its accuracy characteristics. While it is more accurate than naive summation, it can still give large relative errors for ill-conditioned sums.

Suppose that one is summing *n* values *x*_{i}, for . The exact sum is

- (computed with infinite precision).

With compensated summation, one instead obtains , where the error is bounded by^{[2]}

where *?* is the machine precision of the arithmetic being employed (e.g. *?* ? 10^{-16} for IEEE standard double-precision floating point). Usually, the quantity of interest is the relative error , which is therefore bounded above by

In the expression for the relative error bound, the fraction ?|*x _{i}*|/|?

Given a condition number, the relative error of compensated summation is effectively independent of *n*. In principle, there is the O(*n?*^{2}) that grows linearly with *n*, but in practice this term is effectively zero: since the final result is rounded to a precision *?*, the *n?*^{2} term rounds to zero, unless *n* is roughly 1/*?* or larger.^{[2]} In double precision, this corresponds to an *n* of roughly 10^{16}, much larger than most sums. So, for a fixed condition number, the errors of compensated summation are effectively *O*(*?*), independent of *n*.

In comparison, the relative error bound for naive summation (simply adding the numbers in sequence, rounding at each step) grows as multiplied by the condition number.^{[2]} This worst-case error is rarely observed in practice, however, because it only occurs if the rounding errors are all in the same direction. In practice, it is much more likely that the rounding errors have a random sign, with zero mean, so that they form a random walk; in this case, naive summation has a root mean square relative error that grows as multiplied by the condition number.^{[7]} This is still much worse than compensated summation, however. However, if the sum can be performed in twice the precision, then *?* is replaced by *?*^{2}, and naive summation has a worst-case error comparable to the O(*n?*^{2}) term in compensated summation at the original precision.

By the same token, the ?|*x _{i}*| that appears in above is a worst-case bound that occurs only if all the rounding errors have the same sign (and are of maximal possible magnitude).

Neumaier^{[8]} introduced an improved version of Kahan algorithm, which he calls an "improved Kahan-Babu?ka algorithm", which also covers the case when the next term to be added is larger in absolute value than the running sum, effectively swapping the role of what is large and what is small. In pseudocode, the algorithm is:

functionNeumaierSum(input)varsum = 0.0varc = 0.0 // A running compensation for lost low-order bits.fori = 1toinput.lengthdovart = sum + input[i]if|sum| >= |input[i]|thenc += (sum - t) + input[i] // Ifsumis bigger, low-order digits ofinput[i]are lost.elsec += (input[i] - t) + sum // Else low-order digits ofsumare lost.endifsum = tnextireturnsum + c // Correction only applied once in the very end.

For many sequences of numbers, both algorithms agree, but a simple example due to Peters^{[9]} shows how they can differ. For summing in double precision, Kahan's algorithm yields 0.0, whereas Neumaier's algorithm yields the correct value 2.0.

Higher-order modifications of better accuracy are also possible. For example, a variant suggested by Klein,^{[10]} which he called a second-order "iterative Kahan-Babu?ka algorithm". In pseudocode, the algorithm is:

functionKleinSum(input)varsum = 0.0varcs = 0.0varccs = 0.0varcvarccfori = 1toinput.lengthdovart = sum + input[i]if|sum| >= |input[i]|thenc = (sum - t) + input[i]elsec = (input[i] - t) + sumendifsum = t t = cs + cif|cs| >= |c|thencc = (cs - t) + celsecc = (c - t) + csendifcs = t ccs = ccs + ccnextireturnsum + cs + ccs

Although Kahan's algorithm achieves error growth for summing *n* numbers, only slightly worse growth can be achieved by pairwise summation: one recursively divides the set of numbers into two halves, sums each half, and then adds the two sums.^{[2]} This has the advantage of requiring the same number of arithmetic operations as the naive summation (unlike Kahan's algorithm, which requires four times the arithmetic and has a latency of four times a simple summation) and can be calculated in parallel. The base case of the recursion could in principle be the sum of only one (or zero) numbers, but to amortize the overhead of recursion, one would normally use a larger base case. The equivalent of pairwise summation is used in many fast Fourier transform (FFT) algorithms and is responsible for the logarithmic growth of roundoff errors in those FFTs.^{[11]} In practice, with roundoff errors of random signs, the root mean square errors of pairwise summation actually grow as .^{[7]}

Another alternative is to use arbitrary-precision arithmetic, which in principle need no rounding at all with a cost of much greater computational effort. A way of performing exactly rounded sums using arbitrary precision is to extend adaptively using multiple floating-point components. This will minimize computational cost in common cases where high precision is not needed.^{[12]}^{[9]} Another method that uses only integer arithmetic, but a large accumulator, was described by Kirchner and Kulisch;^{[13]} a hardware implementation was described by Müller, Rüb and Rülling.^{[14]}

In principle, a sufficiently aggressive optimizing compiler could destroy the effectiveness of Kahan summation: for example, if the compiler simplified expressions according to the associativity rules of real arithmetic, it might "simplify" the second step in the sequence

`t = sum + y;`

`c = (t - sum) - y;`

to

`c = ((sum + y) - sum) - y;`

and then to

`c = 0;`

thus eliminating the error compensation.^{[15]} In practice, many compilers do not use associativity rules (which are only approximate in floating-point arithmetic) in simplifications, unless explicitly directed to do so by compiler options enabling "unsafe" optimizations,^{[16]}^{[17]}^{[18]}^{[19]} although the Intel C++ Compiler is one example that allows associativity-based transformations by default.^{[20]} The original K&R C version of the C programming language allowed the compiler to re-order floating-point expressions according to real-arithmetic associativity rules, but the subsequent ANSI C standard prohibited re-ordering in order to make C better suited for numerical applications (and more similar to Fortran, which also prohibits re-ordering),^{[21]} although in practice compiler options can re-enable re-ordering, as mentioned above.

A portable way to inhibit such optimizations locally is to break one of the lines in the original formulation into two statements, and make two of the intermediate products volatile:

functionKahanSum(input)varsum = 0.0varc = 0.0fori = 1toinput.lengthdovary = input[i] - cvolatile vart = sum + yvolatile varz = t - sum c = z - y sum = tnextireturnsum

In general, built-in "sum" functions in computer languages typically provide no guarantees that a particular summation algorithm will be employed, much less Kahan summation.^{[]} The BLAS standard for linear algebra subroutines explicitly avoids mandating any particular computational order of operations for performance reasons,^{[22]} and BLAS implementations typically do not use Kahan summation.

The standard library of the Python computer language specifies an fsum function for exactly rounded summation, using the Shewchuk algorithm^{[9]} to track multiple partial sums.

In the Julia language, the default implementation of the `sum`

function does pairwise summation for high accuracy with good performance,^{[23]} but an external library provides an implementation of Neumaier's variant named `sum_kbn`

for the cases when higher accuracy is needed.^{[24]}

In the C# language, HPCsharp nuget package implements the Neumaier variant and pairwise summation: both as scalar, data-parallel using SIMD processor instructions, and parallel multi-core.^{[25]}

- Algorithms for calculating variance, which includes stable summation

**^**Strictly, there exist other variants of compensated summation as well: see Higham, Nicholas (2002).*Accuracy and Stability of Numerical Algorithms (2 ed)*. SIAM. pp. 110-123. ISBN 978-0-89871-521-7.- ^
^{a}^{b}^{c}^{d}^{e}^{f}^{g}^{h}Higham, Nicholas J. (1993), "The accuracy of floating point summation" (PDF),*SIAM Journal on Scientific Computing*,**14**(4): 783-799, CiteSeerX 10.1.1.43.3535, doi:10.1137/0914050, S2CID 14071038. **^**Kahan, William (January 1965), "Further remarks on reducing truncation errors" (PDF),*Communications of the ACM*,**8**(1): 40, doi:10.1145/363707.363723, S2CID 22584810, archived from the original (PDF) on 9 February 2018.**^**Bresenham, Jack E. (January 1965). "Algorithm for computer control of a digital plotter" (PDF).*IBM Systems Journal*.**4**(1): 25-30. doi:10.1147/sj.41.0025.**^**Inose, H.; Yasuda, Y.; Murakami, J. (September 1962). "A Telemetering System by Code Manipulation - Modulation".*IRE Transactions on Space Electronics and Telemetry*: 204-209. doi:10.1109/IRET-SET.1962.5008839. S2CID 51647729.**^**Trefethen, Lloyd N.; Bau, David (1997).*Numerical Linear Algebra*. Philadelphia: SIAM. ISBN 978-0-89871-361-9.- ^
^{a}^{b}Manfred Tasche and Hansmartin Zeuner,*Handbook of Analytic-Computational Methods in Applied Mathematics*, Boca Raton, FL: CRC Press, 2000. **^**Neumaier, A. (1974). "Rundungsfehleranalyse einiger Verfahren zur Summation endlicher Summen" [Rounding Error Analysis of Some Methods for Summing Finite Sums] (PDF).*Zeitschrift für Angewandte Mathematik und Mechanik*(in German).**54**(1): 39-51. Bibcode:1974ZaMM...54...39N. doi:10.1002/zamm.19740540106.- ^
^{a}^{b}^{c}Raymond Hettinger, Recipe 393090: Binary floating point summation accurate to full precision, Python implementation of algorithm from Shewchuk (1997) article (28 March 2005). **^**A., Klein (2006). "A generalized Kahan-Babu?ka-Summation-Algorithm".*Computing*. Springer-Verlag.**76**(3-4): 279-293. doi:10.1007/s00607-005-0139-x. S2CID 4561254.**^**S. G. Johnson and M. Frigo, "Implementing FFTs in practice, in*Fast Fourier Transforms*, edited by C. Sidney Burrus(2008).**^**Jonathan R. Shewchuk, Adaptive Precision Floating-Point Arithmetic and Fast Robust Geometric Predicates,*Discrete and Computational Geometry*, vol. 18, pp. 305-363 (October 1997).**^**R. Kirchner, Ulrich W. Kulisch,*Accurate arithmetic for vector processors*, Journal of Parallel and Distributed Computing 5 (1988) 250-270.**^**M. Muller, C. Rub, W. Rulling [1],*Exact accumulation of floating-point numbers*, Proceedings 10th IEEE Symposium on Computer Arithmetic (Jun 1991), doi:10.1109/ARITH.1991.145535.**^**Goldberg, David (March 1991), "What every computer scientist should know about floating-point arithmetic" (PDF),*ACM Computing Surveys*,**23**(1): 5-48, doi:10.1145/103162.103163.**^**GNU Compiler Collection manual, version 4.4.3: 3.10 Options That Control Optimization,*-fassociative-math*(Jan. 21, 2010).**^***Compaq Fortran User Manual for Tru64 UNIX and Linux Alpha Systems Archived 2011-06-07 at the Wayback Machine*, section 5.9.7 Arithmetic Reordering Optimizations (retrieved March 2010).**^**Börje Lindh, Application Performance Optimization,*Sun BluePrints OnLine*(March 2002).**^**Eric Fleegal, "Microsoft Visual C++ Floating-Point Optimization",*Microsoft Visual Studio Technical Articles*(June 2004).**^**Martyn J. Corden, "Consistency of floating-point results using the Intel compiler",*Intel technical report*(Sep. 18, 2009).**^**MacDonald, Tom (1991). "C for Numerical Computing".*Journal of Supercomputing*.**5**(1): 31-48. doi:10.1007/BF00155856. S2CID 27876900.**^**BLAS Technical Forum, section 2.7 (August 21, 2001), Archived on Wayback Machine.**^**RFC: use pairwise summation for sum, cumsum, and cumprod, github.com/JuliaLang/julia pull request #4039 (August 2013).**^**KahanSummation library in Julia.**^**HPCsharp nuget package of high performance algorithms.

This article uses material from the Wikipedia page available here. It is released under the Creative Commons Attribution-Share-Alike License 3.0.

Popular Products

Music Scenes

Popular Artists