Kahan summation algorithm (source code)

= Kahan summation algorithm
{c}

= Kahan summation
{c}
{synonym}

= Compensated (Kahan) summation
{synonym}

= Kahan compensated summation
{c}
{synonym}

The <Kahan summation algorithm> computes a <sum> in <floating-point arithmetic> while carrying a correction for low-order information lost by successive <additions>. With accumulator $s$ and correction $c$ initially zero, process each input $x$ in this order:
``
y = x - c
t = s + y
c = (t - s) - y
s = t
``
Every operation shown is rounded in the working <floating-point representation>. The new $c$ approximates the portion added too much or too little in the rounded $s+y$, so the next input subtracts it. For binary64 inputs $1,2^{-53},2^{-53}$ in that order, ordinary left-to-right <summation> loses both small increments, returning one; this <algorithm> recovers $1+2^{-52}$.

The correction substantially improves many long <sums>, but is not an exact <summation> method and does not remove ill-conditioning when large opposite-sign terms nearly cancel. Its operation order is essential: a compiler that rewrites $(t-s)-y$ as exact algebraic zero destroys the correction.https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html[Goldberg, Errors in Summation and Optimizers: compensated summation and why reassociation invalidates it]{ref}