I recently fixed a rounding problem in moyo by replacing a 3x3 matrix product with a compensated one (PR #536). The compensated product is Algorithm 5.3 (Dot2) of Ogita, Rump, and Oishi, “Accurate Sum and Dot Product”, SIAM J. Sci. Comput. 26(6), 1955-1988 (2005). It is a short loop with no branches, and it returns the dot product as if it had been computed in twice the working precision and then rounded to a double.

This post is my attempt to understand why it works. The whole algorithm rests on one building block, 2Sum, so most of the post is about that.

Throughout, a formula such as \(a + b\) means the exact real number, \(\mathrm{fl}(a + b)\) means that number rounded to the nearest double, and an expression in code font such as a + b is evaluated in floating point.

The problem: cancellation

One example

Take \(m = 2^{27}\) and compute \((m + 1)^2 + 0.5^2 - m (m + 2)\) as a dot product \(x^\top y\) of length 3 with

\[x = (m + 1,\ 0.5,\ -m), \qquad y = (m + 1,\ 0.5,\ m + 2).\]

Since \((m + 1)^2 - m (m + 2) = 1\), the exact answer is 1.25. In double precision the plain loop returns 0.

Two things go wrong. \((m + 1)^2 = 2^{54} + 2^{28} + 1\) needs 55 bits, so the product is rounded and the final 1 is lost. Then 0.25 is added to a number of size \(2^{54}\), where the spacing between doubles is 4, and it is lost as well. The last term cancels everything that is left.

The general bound

The example is one instance of a general fact. The following bound is a theorem about the plain loop: it holds for every pair of vectors of doubles, whatever their values, as long as nothing overflows or underflows. Its derivation is in the appendix.

Let \(x\) and \(y\) have length \(n\), let \(x^\top y\) be the exact dot product, and let \(\mathrm{res}\) be what the plain loop returns. Then

\[\lvert \mathrm{res} - x^\top y \rvert \le \gamma_n \lvert x \rvert^\top \lvert y \rvert, \qquad \gamma_n = \frac{n\,\mathrm{eps}}{1 - n\,\mathrm{eps}}, \qquad \mathrm{eps} = 2^{-53}. \label{eq:plain-bound}\]

The two factors on the right are:

  • \(\gamma_n\), which is about \(n \times 1.1 \times 10^{-16}\). It depends only on the length.
  • \(\lvert x \rvert^\top \lvert y \rvert = \sum_k \lvert x_k y_k \rvert\), the sum of the magnitudes of the terms. Nothing cancels in it.

So \(\eqref{eq:plain-bound}\) says that the error is a tiny fraction of the sum of the magnitudes of the terms. It does not say that the error is a tiny fraction of the result. When the terms cancel, the result is much smaller than that sum, and an error that is tiny next to the terms can be large next to the result.

The condition number of the dot product is defined as the ratio of the two sizes, times two:

\[\mathrm{cond} := \frac{2 \lvert x \rvert^\top \lvert y \rvert}{\lvert x^\top y \rvert}. \label{eq:cond}\]

With this definition, dividing \(\eqref{eq:plain-bound}\) by \(\lvert x^\top y \rvert\) turns it into a bound on the relative error:

\[\frac{\lvert \mathrm{res} - x^\top y \rvert}{\lvert x^\top y \rvert} \le \frac{\gamma_n}{2}\,\mathrm{cond}. \label{eq:plain-relative}\]

If all terms have the same sign, nothing cancels, \(\mathrm{cond} = 2\), and the plain loop is accurate to about \(\gamma_n\). The factor 2 in the definition \(\eqref{eq:cond}\) is a convention: it makes \(\mathrm{cond}\) the factor by which a relative perturbation of all the entries of \(x\) and \(y\) can be amplified in the result.

The bound applied to the example

In the example, \(n = 3\), so \(\gamma_3 \approx 3.3 \times 10^{-16}\), and \(\lvert x \rvert^\top \lvert y \rvert \approx 3.6 \times 10^{16}\). The bound \(\eqref{eq:plain-bound}\) allows an absolute error of up to about 12, for a result that is 1.25. It guarantees no digit at all, and the loop indeed returned 0, an error of 1.25. The condition number \(\eqref{eq:cond}\) is \(5.8 \times 10^{16}\).

The bound against measurements

The bound is a worst case, but it is not pessimistic. The figure shows the measured relative error of the plain loop for 2000 random dot products of length 10, generated with a prescribed amount of cancellation and compared against rational arithmetic. The dashed line is the right-hand side of \(\eqref{eq:plain-relative}\). The second appendix describes how the dot products are generated.

Relative error of the plain dot product against the condition number, on logarithmic axes. The points follow a straight line of slope one, about a factor of ten below the bound, and cross relative error one near a condition number of 1e16.

The error grows in proportion to the condition number and stays about a factor of ten below the bound. Every factor of ten in \(\mathrm{cond}\) costs one decimal digit, and at \(\mathrm{cond} \approx 10^{16}\) the sixteen digits of a double are used up.

2Sum: the rounding error of a sum is a double

Let \(a\) and \(b\) be doubles, and let \(x = \mathrm{fl}(a + b)\) be their floating-point sum. The operands are exact; the only rounding is in the addition. The rounding error \(y = a + b - x\) is itself a double, and five more floating-point operations compute it:

/// Return `(x, y)` with `x = fl(a + b)` and `x + y = a + b` exactly.
fn two_sum(a: f64, b: f64) -> (f64, f64) {
    let x = a + b;
    let z = x - a;
    let y = (a - (x - z)) + (b - z);
    (x, y)
}

This is 2Sum. The pair \((x, y)\) represents \(a + b\) with no error, which is why it is called an error-free transformation. It holds under round-to-nearest, the IEEE 754 default, as long as the sum does not overflow.

Why the error is a double

The figure shows \(a \ge b > 0\) for toy doubles with 6 significant bits where a real double has 53.

Bit layout of a floating-point addition with 6-bit toy doubles. a = 45 occupies six bits. b = 5.375 also occupies six bits, shifted three places to the right. The exact sum 50.375 needs nine bits. x = 50 keeps the leading six, and the error y = 0.375 is the three remaining bits, which are the low bits of b.

The exact sum needs more bits than a double has. The addition keeps the leading ones as \(x\), and the error \(y\) is what is left over on the right: the low bits of \(b\) that \(x\) has no room for. Those are fewer bits than \(b\) itself has, so they fit in a double. When the sum is rounded up instead of down, \(y\) is that leftover minus one unit of the last bit of \(x\), which is still a whole number of units of \(b\) and still no larger than \(b\) in magnitude.

How the five operations find it

Near \(10^{16}\), consecutive doubles are 2 apart. For \(a = 10^{16}\) and \(b = 3.25\), the addition returns \(10^{16} + 4\): it was asked to add 3.25 and added 4, so the error is \(-0.75\).

operation value what it means can it round?
x = a + b \(10^{16} + 4\) the rounded sum yes: this is the error being measured
z = x - a \(4\) what was actually added to a only if a is the smaller operand
x - z \(10^{16}\) what remains of x without that never
a - (x - z) \(0\) a lost nothing never
b - z \(-0.75\) b was 3.25, and 4 was added in its place never
y, their sum \(-0.75\) the rounding error never

Rounding enters in the first two operations only. The last column is what I measured on a million random pairs of doubles: the addition rounded in 64% of them, z = x - a rounded in 31%, always with \(\lvert a \rvert < \lvert b \rvert\), and the other four operations never rounded.

The operations split x into two shares, z credited to b and x - z credited to a, and compare each operand with its share:

\[\underbrace{a - (x - z)}_{\text{what } a \text{ lost}} + \underbrace{b - z}_{\text{what } b \text{ lost}} = a + b - x. \label{eq:shares}\]

In real numbers \(\eqref{eq:shares}\) holds for every \(z\), because \(z\) cancels. The choice z = x - a matters only because it makes each share nearly equal to its operand, so that the subtractions in \(\eqref{eq:shares}\) do not round. So a rounded z is harmless: with the operands swapped, z rounds to \(10^{16}\) and y is still \(-0.75\). That the result is exact for all inputs is the theorem behind 2Sum; I do not prove it here.

When the larger operand is known in advance, three operations are enough; that variant, FastTwoSum, is in the appendix.

TwoProduct: the same for a product

A product has the same property: if \(x = \mathrm{fl}(a b)\), then \(a b - x\) is a double, provided nothing underflows. The figure shows why, again for toy doubles with 6 significant bits.

Bit layout of a floating-point multiplication with 6-bit toy doubles. a = 45 and b = 43 each occupy six bits. The exact product 1935 needs eleven bits. x = 1920 keeps the leading six, and the error y = 15 is the five remaining bits.

The exact product of two 6-bit numbers needs up to 12 bits. The multiplication keeps the leading 6 as \(x\), and the error \(y\) is the rest: at most 6 bits, so it fits in a double. As for the sum, rounding up instead of down changes \(y\) by one unit of the last bit of \(x\), and it still fits.

With a fused multiply-add the error takes one operation. a.mul_add(b, -x) computes \(a b - x\) with a single rounding at the end, and since the exact value is representable, that rounding changes nothing:

/// Return `(x, y)` with `x = fl(a * b)` and `x + y = a * b` exactly, if no underflow occurs.
fn two_product(a: f64, b: f64) -> (f64, f64) {
    let x = a * b;
    let y = a.mul_add(b, -x);
    (x, y)
}

This is Algorithm 3.5 (TwoProductFMA) of the paper. In the example above, two_product(m + 1, m + 1) returns \((2^{54} + 2^{28},\ 1)\): the lost 1 is back.

Dot2

With the two helpers, the algorithm is short:

fn dot2(x: &[f64], y: &[f64]) -> f64 {
    let (mut p, mut s) = two_product(x[0], y[0]);
    for k in 1..x.len() {
        let (h, r) = two_product(x[k], y[k]);
        let (next_p, q) = two_sum(p, h);
        p = next_p;
        s += q + r;
    }
    p + s
}

Two accumulators run side by side.

p goes through exactly the operations of the plain loop: round each product, add it to the running sum, round again. At the end of the loop, p is the plain dot product, bit for bit.

s collects what those operations throw away: r is the rounding error of the product, and q is the rounding error of adding it to p.

The identity behind it

Write \(h_k\), \(r_k\), \(p_k\), \(q_k\) for the values after the \(k\)-th term, with \(p_1 = h_1\). The two error-free transformations say, exactly,

\[\begin{aligned} x_k y_k &= h_k + r_k && (k = 1, \dots, n), \\ p_{k-1} + h_k &= p_k + q_k && (k = 2, \dots, n). \end{aligned} \label{eq:eft}\]

Summing the first line of \(\eqref{eq:eft}\) over \(k\) and telescoping the second gives

\[x^\top y = p_n + \Bigl( r_1 + \sum_{k=2}^{n} (q_k + r_k) \Bigr). \label{eq:identity}\]

Equation \(\eqref{eq:identity}\) is an equality between real numbers, with no approximation in it. The exact dot product is the plain result \(p_n\) plus a sum of \(2n - 1\) doubles, and the algorithm holds every one of them in its hands. The sum in parentheses is precisely the error of the plain dot product.

So Dot2 does not compute the dot product more carefully. It computes it as carelessly as the plain loop does, computes the resulting error on the side, and adds the two at the end.

The trace of the example shows it:

\(k\) \(x_k y_k\) \(h_k\) \(r_k\) \(p_k\) \(q_k\) s
1 \(2^{54} + 2^{28} + 1\) \(2^{54} + 2^{28}\) 1 \(2^{54} + 2^{28}\)   1
2 0.25 0.25 0 \(2^{54} + 2^{28}\) 0.25 1.25
3 \(-(2^{54} + 2^{28})\) \(-(2^{54} + 2^{28})\) 0 0 0 1.25

The plain result is \(p_3 = 0\), its error is 1.25, and p + s returns the exact answer 1.25.

What still rounds

Since \(\eqref{eq:identity}\) is exact, Dot2 loses accuracy in only two places: the additions that accumulate s, and the final p + s. The paper bounds the result (Proposition 5.5, if no underflow occurs):

\[\lvert \mathrm{res} - x^\top y \rvert \le \mathrm{eps}\, \lvert x^\top y \rvert + \gamma_n^2\, \lvert x \rvert^\top \lvert y \rvert. \label{eq:dot2-bound}\]

The first term is the unavoidable rounding of the result to a double. The second is the plain bound \(\eqref{eq:plain-bound}\) with one more factor of \(\gamma_n\), which is what a computation with 106 bits would give. So the result is accurate to the last bit or so as long as \(\mathrm{cond}\) is well below \(1 / \mathrm{eps} \approx 10^{16}\), and no digit is left near \(1 / \mathrm{eps}^2 \approx 10^{32}\). The same paper gives DotK for K-fold precision when that is not enough.

Measuring it

The figure repeats the measurement of the plain dot product with Dot2 next to it, on condition numbers up to \(10^{32}\). The second appendix describes how the dot products are generated.

Relative error of the plain dot product and of Dot2 against the condition number, on logarithmic axes. The plain errors follow a straight line of slope one and cross relative error one near a condition number of 1e16. The Dot2 errors stay flat near 1e-16 up to a condition number of 1e16, then follow a parallel line sixteen orders of magnitude below the plain errors, reaching relative error one near 1e32. Each set of points lies below its bound.

The Dot2 points are the plain points shifted down by sixteen orders of magnitude, with a floor near \(\mathrm{eps} = 1.1 \times 10^{-16}\). Below \(\mathrm{cond} = 10^{16}\), every Dot2 result in the sample is within \(\mathrm{eps}\) relative error of the exact value.

What it costs

Per term, the plain loop does a multiplication and an addition. Dot2 does a multiplication, a fused multiply-add, the six operations of 2Sum, and two more additions: ten operations instead of two, no branches, no extra memory, and no sorting of the input. Without a fused multiply-add, the product error has to be computed by splitting each factor into two halves, a technique that also goes back to Dekker and that the paper counts as 17 operations for TwoProduct.

Compared with Kahan’s compensated summation, the error of each addition is captured exactly by 2Sum and kept in a separate accumulator, instead of being computed by Dekker’s three operations, whose precondition the loop does not guarantee, and fed back into the next term. Compared with a double-double accumulator, the low-order part is summed with plain additions and never renormalized, which makes it cheaper.

Where I needed it

In moyo, the Niggli reduction recomputes the cell after every step as basis * trans_mat, where trans_mat is an exact integer matrix. For a heavily sheared basis, both factors have entries of a few thousand while the reduced cell has entries of order 1 to 30, so every entry of the product is a dot product of length 3 whose terms, of order \(10^{7}\), cancel almost completely. The plain product left errors of about \(10^{-9}\) that differed from one trans_mat to the next, and the reduction, which compares cells with a tolerance of \(10^{-8}\), ended up cycling.

For the transformation that takes the basis of the issue to its reduced cell, I measured:

  bound maximum error of an entry
plain product \(4.3 \times 10^{-9}\) \(2.5 \times 10^{-10}\)
Dot2 \(1.4 \times 10^{-24}\) plus the final rounding 0

Every entry computed by Dot2 equals the exact product rounded to a double. Its absolute bound of \(1.4 \times 10^{-24}\) is far below anything the reduction compares, so for this use it behaves as an exact product.

Appendix: where the plain bound comes from

The derivation of \(\eqref{eq:plain-bound}\) needs one property of floating-point arithmetic. Each operation returns the exact result with a relative error of at most \(\mathrm{eps}\):

\[\mathrm{fl}(a + b) = (a + b)(1 + \delta), \qquad \mathrm{fl}(a b) = a b\,(1 + \delta), \qquad \lvert \delta \rvert \le \mathrm{eps}. \label{eq:model}\]

This is what rounding to nearest means, as long as nothing overflows or underflows.

Now follow the plain loop. Let \(s_k\) be the running sum after \(k\) terms, \(\delta_k\) the relative error of the \(k\)-th product, and \(\varepsilon_k\) that of the \(k\)-th addition. By \(\eqref{eq:model}\),

\[\begin{aligned} s_1 &= x_1 y_1 (1 + \delta_1), \\ s_k &= \bigl( s_{k-1} + x_k y_k (1 + \delta_k) \bigr)(1 + \varepsilon_k) \quad (k = 2, \dots, n). \end{aligned} \label{eq:recurrence}\]

Unrolling the recurrence for \(n = 3\) shows the pattern:

\[\begin{aligned} \mathrm{res} = s_3 &= x_1 y_1 (1 + \delta_1)(1 + \varepsilon_2)(1 + \varepsilon_3) \\ &+ x_2 y_2 (1 + \delta_2)(1 + \varepsilon_2)(1 + \varepsilon_3) \\ &+ x_3 y_3 (1 + \delta_3)(1 + \varepsilon_3). \end{aligned} \label{eq:unrolled}\]

Each term \(x_k y_k\) appears exactly once, multiplied by one factor for its own product and one factor for every addition it passes through afterwards. For general \(n\) no term collects more than \(n\) such factors.

A product of \(n\) factors, each within \(\mathrm{eps}\) of 1, is within about \(n\,\mathrm{eps}\) of 1. The precise version, with the higher-order terms included, is

\[\prod_{i=1}^{n} (1 + \delta_i) = 1 + \theta, \qquad \lvert \theta \rvert \le \frac{n\,\mathrm{eps}}{1 - n\,\mathrm{eps}} = \gamma_n, \label{eq:gamma}\]

which is where \(\gamma_n\) comes from. So the computed result is the exact dot product of slightly perturbed terms,

\[\mathrm{res} = \sum_{k=1}^{n} x_k y_k (1 + \theta_k), \qquad \lvert \theta_k \rvert \le \gamma_n. \label{eq:perturbed}\]

Subtracting \(x^\top y = \sum_k x_k y_k\) and taking absolute values gives

\[\lvert \mathrm{res} - x^\top y \rvert = \Bigl\lvert \sum_{k=1}^{n} x_k y_k\, \theta_k \Bigr\rvert \le \gamma_n \sum_{k=1}^{n} \lvert x_k y_k \rvert,\]

which is \(\eqref{eq:plain-bound}\).

The last step is where cancellation enters. The perturbations \(\theta_k\) have unrelated signs, so the errors \(x_k y_k \theta_k\) do not cancel even when the terms \(x_k y_k\) do. That is why the right-hand side has \(\lvert x \rvert^\top \lvert y \rvert\) and not \(\lvert x^\top y \rvert\).

Appendix: how the figures are generated

The first figure needs dot products whose condition number is spread evenly, on a logarithmic scale, from 1 to \(10^{20}\). Random vectors do not provide them: their terms rarely cancel, so their condition numbers stay small. The cancellation has to be built in. The construction below follows the idea of the generator GenDot in the paper.

Each of the 2000 samples is a pair of vectors of length \(n = 10\), generated in three steps.

  1. Draw a number of bits \(b\) uniformly from \([2, 66]\). The sample is meant to have a condition number of roughly \(2^b\).
  2. Fill the first five entries with large terms. For \(k = 1, \dots, 5\), draw an exponent \(e_k\) uniformly from \([0, b/2]\), with \(e_1 = b/2\) so that the largest size is always present, and set \(x_k = u\, 2^{e_k}\) and \(y_k = u'\, 2^{e_k}\) with \(u\) and \(u'\) uniform in \((-1, 1)\). The products \(x_k y_k\) are then as large as \(2^b\).
  3. Fill the last five entries so that they cancel the first five. For \(k = 6, \dots, 10\), let the exponent \(e_k\) decrease linearly from \(b/2\) to 0, draw \(x_k = u\, 2^{e_k}\) and a target \(t_k = u'\, 2^{e_k}\), and choose \(y_k\) so that the partial dot product up to \(k\) equals the target:
\[y_k = \mathrm{fl}\!\left( \frac{t_k - \sum_{j < k} x_j y_j}{x_k} \right). \label{eq:gendot}\]

The sum in \(\eqref{eq:gendot}\) is evaluated exactly, in rational arithmetic, and only the quotient is rounded to a double. The targets shrink from \(2^{b/2}\) to order 1, so the final dot product is of order 1 while its terms are as large as \(2^b\).

Once the vectors are fixed, they are ordinary doubles, and everything about them is measured, not assumed. Every double is a rational number, so Python’s fractions.Fraction gives the exact dot product \(x^\top y\) and the exact \(\lvert x \rvert^\top \lvert y \rvert\) of the vectors as generated. From these, each point in the figure is:

  • horizontally, the condition number \(\eqref{eq:cond}\) of the sample, computed exactly. The value \(2^b\) of step 1 only steers the generator and is not plotted.
  • vertically, the relative error \(\lvert \mathrm{res} - x^\top y \rvert / \lvert x^\top y \rvert\), where \(\mathrm{res}\) is the result of the plain loop in Python floats, which are IEEE doubles like f64 in Rust. The difference is also taken exactly.

A sample whose exact dot product or whose error is zero cannot be drawn on logarithmic axes and would be skipped; none of the 2000 was. A few samples have a condition number above \(10^{20}\) and fall outside the frame.

The figure with Dot2 uses the same construction with \(b\) drawn from \([2, 106]\) and another 2000 samples, and plots the relative error of both algorithms for each sample. The error \(y\) of TwoProduct is computed in rational arithmetic and converted to a float, which is exact because \(y\) is a double.

The random seeds are fixed, so the figures are reproducible.

The script is _scripts/dot2_error_vs_cond.py in the repository of this site.

Appendix: FastTwoSum, Dekker’s three-operation version

There are two algorithms for the error of a sum, and the paper lists both: TwoSum, credited to Knuth, is the six-operation one of the main text, and FastTwoSum, credited to Dekker, takes three. Wikipedia calls them 2Sum and Fast2Sum.

/// Return `(x, y)` with `x = fl(a + b)` and `x + y = a + b` exactly, provided `|a| >= |b|`.
fn fast_two_sum(a: f64, b: f64) -> (f64, f64) {
    let x = a + b;
    let z = x - a;
    let y = b - z;
    (x, y)
}

The two start the same way: z = x - a is the part of b that arrived in x, and b - z is the part that did not. Dekker’s version stops there. That is correct when a is the larger operand, because then x - a is computed without rounding.

When a is the smaller operand, x - a can round, and the result is wrong. For \(a = 10^{-16}\) and \(b = 1\), the sum is x = 1.0, but x - a rounds to 0.9999999999999999, and Dekker’s version returns an error of \(1.11 \times 10^{-16}\) where the true error is \(10^{-16}\). On 200,000 random pairs with no ordering, it was inexact for 46% of them.

Knuth’s version adds the mirror-image term a - (x - z): the part of a that did not arrive in x. When \(\lvert a \rvert \ge \lvert b \rvert\), x - z returns a exactly, this term is zero, and the two algorithms return the same result. So Knuth’s version is Dekker’s plus three operations that repair the case Dekker’s excludes.

  Dekker (FastTwoSum) Knuth (TwoSum)
floating-point operations 3 6
precondition \(a\) is the larger operand in magnitude none
for unordered input compare and swap first nothing to do

The choice is between a branch and three additions. In Dot2 the operands are the running sum p and the next product h, and either can be the larger one, so Dekker’s version would need a comparison in every iteration. A branch that the processor cannot predict costs more than three additions and prevents the loop from being vectorized, which is why the paper uses Knuth’s version, and so does moyo. Dekker’s version is the right one where the ordering comes for free, for example when renormalizing a double-double number whose high part dominates by construction.

On the history, the Wikipedia article says that both algorithms were first published by Ole Møller in 1965. The three-operation form is implicit in Kahan’s compensated summation of the same year, Dekker factored it out in 1971 for double-double arithmetic, and the names 2Sum and Fast2Sum seem to go back to Shewchuk in 1997.