Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

Correctness in Finite Precision

Integer overflow, floating point and robust predicates: when correct math gives wrong answers.

On February 25, 1991, a Patriot missile battery at Dhahran failed to intercept an incoming Scud. Its clock counted tenths of a second, and 0.1 has no finite binary expansion: chopped to fit a 24-bit register, each tick lost about 9.5×10−89.5 \times 10^{-8} seconds, and after 100 hours of operation the clock was off by about a third of a second. Correct mathematics, run on finite numbers, gave a wrong answer. This lesson is about when that happens, and how to keep algorithms correct anyway.

What you’ll learn

  • Predict integer overflow in fixed-width arithmetic, and write midpoints, products and modular arithmetic that cannot overflow.
  • Explain IEEE 754 double precision, the unit roundoff and the standard model of rounding, and recognize cancellation and non-associativity.
  • Bound the error of recursive, pairwise and compensated summation, and implement Kahan's algorithm.
  • Make geometric predicates and binary search on real numbers robust.

Integers overflow

Machine integers have a fixed width ww. Unsigned ones live in [0,2w)[0, 2^w) and their arithmetic wraps around modulo 2w2^w; signed ones use two's complement, with range [−2w−1,2w−1)[-2^{w-1}, 2^{w-1}). A 32-bit int ends at 231−1=2,147,483,6472^{31} - 1 = 2{,}147{,}483{,}647, just over 2×1092 \times 10^9: three values of 10910^9 already overflow when added, and 50000⋅50000=2.5×10950000 \cdot 50000 = 2.5 \times 10^9 does not fit either.

In C and C++, signed integer overflow is undefined behavior, not wraparound: the compiler may assume it never happens, so even a check like if (x + 1 < x) can be optimized away. Java defines signed overflow to wrap. Python's integers are unbounded and never overflow, at a price in speed.

cpp
#include <cstdio>

long long mulmod(long long a, long long b, long long m) {   // 0 <= a, b < m <= 1e18
    return (long long)((__int128)a * b % m);                // __int128: a GCC/Clang extension
}

int main() {
    int lo = 1500000000, hi = 2000000000;
    int mid = lo + (hi - lo) / 2;          // safe; (lo + hi) / 2 would overflow int
    long long c = 50000LL * 50000;         // widen BEFORE multiplying
    int r;
    bool overflow = __builtin_mul_overflow(50000, 50000, &r);   // GCC/Clang builtin
    std::printf("%d %lld %d %lld\n", mid, c, (int)overflow,
                mulmod(999999999999999999LL, 999999999999999998LL, 1000000000000000003LL));
}

It prints 1750000000 2500000000 1 20. The common contest modulus 109+710^9 + 7 is chosen so that a sum of two residues fits in a signed 32-bit int and a product of two fits in a signed 64-bit long long: (109+7)2≈1.0×1018<263≈9.2×1018(10^9 + 7)^2 \approx 1.0 \times 10^{18} < 2^{63} \approx 9.2 \times 10^{18}. Moduli near 101810^{18} need 128-bit products.

Check your understanding

In C++, int a = 50000, b = 50000; long long c = a * b; What does c hold?

  1. 2,500,000,000, because c is a long long
  2. Nothing defined: a * b is computed as an int and overflows before the conversion, which is undefined behavior (in practice usually −1,794,967,296-1{,}794{,}967{,}296)
  3. 0
  4. It does not compile
Show the answer

B. Nothing defined: a * b is computed as an int and overflows before the conversion, which is undefined behavior (in practice usually −1,794,967,296-1{,}794{,}967{,}296)

The type of a * b is decided by its operands, both int, and the conversion to long long happens only after the multiplication has overflowed. Write (long long)a * b to widen first.

What a double is

A double-precision floating-point number (IEEE 754 binary64) has a sign bit, 11 exponent bits and 52 stored fraction bits, which with an implicit leading 1 make a 53-bit significand: x=±(1.f)2×2ex = \pm(1.f)_2 \times 2^e. Every integer up to 253=9,007,199,254,740,9922^{53} = 9{,}007{,}199{,}254{,}740{,}992 is exact, but 253+12^{53} + 1 is not representable. Each basic operation is computed exactly and then rounded to the nearest double, which gives the standard model of rounding error:

fl(x∘y)=(x∘y)(1+δ),∣δ∣≤u=2−53≈1.11×10−16,\mathrm{fl}(x \circ y) = (x \circ y)(1 + \delta), \qquad |\delta| \le u = 2^{-53} \approx 1.11 \times 10^{-16},

for ∘∈{+,−,×,/}\circ \in \{+, -, \times, /\}, barring overflow and underflow. The unit roundoff uu is half of machine epsilon, ε=2−52≈2.22×10−16\varepsilon = 2^{-52} \approx 2.22 \times 10^{-16}, the gap between 1 and the next double.

ExpressionIn doublesWhy
0.1 + 0.2 == 0.3False: the sum is 0.300000000000000040.1, 0.2 and 0.3 are not representable, and the rounding errors do not cancel
(1e16 + 1) - 1e160.0, while (1e16 - 1e16) + 1 is 1.0near 101610^{16} consecutive doubles are 2 apart, so the 1 is rounded away: addition is not associative
(1 - cos(x)) / x**2 at x = 1e-80.0 instead of 0.50.5cos⁡x\cos x rounds to exactly 1, and subtracting nearly equal numbers, cancellation, exposes the earlier rounding
The third one is fixed by rewriting the formula: 1−cos⁡x=2sin⁡2(x/2)1 - \cos x = 2\sin^2(x/2), and 2 * sin(x/2)**2 / x**2 gives 0.5. Stable formulas avoid subtracting nearly equal computed quantities.

Summing many numbers

Adding nn numbers one after another, recursive summation, makes n−1n - 1 roundings, each up to uu times a partial sum. To first order in uu the error obeys

∣s^−∑ixi∣  ≤  (n−1) u∑i∣xi∣+O(u2).\Big|\hat s - \sum_i x_i\Big| \;\le\; (n - 1)\,u \sum_i |x_i| + O(u^2).

Adding in a balanced binary tree, pairwise summation, sends each xix_i through only ⌈log⁡2n⌉\lceil \log_2 n \rceil additions, and the factor n−1n - 1 becomes ⌈log⁡2n⌉\lceil \log_2 n \rceil. Kahan's compensated summation (1965) does better still, with a few extra operations per term: it captures the low-order bits that each addition loses and feeds them into the next.

DerivationProof of the recursive summation bound
  1. s^k=(s^k−1+xk)(1+δk),∣δk∣≤u\hat s_k = (\hat s_{k-1} + x_k)(1 + \delta_k), \qquad |\delta_k| \le u

    One rounding per addition. Let s^1=x1\hat s_1 = x_1 and s^k=fl(s^k−1+xk)\hat s_k = \mathrm{fl}(\hat s_{k-1} + x_k). By the standard model,

  2. s^n=∑i=1nxi∏k=max⁡(i,2)n(1+δk)\hat s_n = \sum_{i=1}^{n} x_i \prod_{k=\max(i,2)}^{n} (1 + \delta_k)

    Unroll. Each xix_i is rounded again by every later addition: x1x_1 and x2x_2 by additions 2,…,n2, \dots, n, and xix_i by additions i,…,ni, \dots, n. So

  3. ∣s^n−∑ixi∣  ≤  γn−1∑i∣xi∣  =  (n−1) u1−(n−1) u∑i∣xi∣  =  (n−1) u∑i∣xi∣+O(u2)\Big|\hat s_n - \sum_{i} x_i\Big| \;\le\; \gamma_{n-1}\sum_{i}|x_i| \;=\; \frac{(n-1)\,u}{1 - (n-1)\,u}\sum_{i}|x_i| \;=\; (n-1)\,u\sum_i|x_i| + O(u^2)

    Bound the products. A product of mm factors 1+δk1 + \delta_k with ∣δk∣≤u|\delta_k| \le u and mu<1mu < 1 equals 1+θm1 + \theta_m with ∣θm∣≤γm=mu1−mu|\theta_m| \le \gamma_m = \frac{mu}{1 - mu}, and every xix_i carries at most n−1n - 1 factors:

  4. Pairwise summation sends each xix_i through at most ⌈log⁡2n⌉\lceil \log_2 n \rceil additions, so the same argument gives γ⌈log⁡2n⌉\gamma_{\lceil \log_2 n \rceil} instead of γn−1\gamma_{n-1}. The proof also shows where the error comes from: the early terms are rounded again at every later addition, which is exactly what compensation repairs.

python
def kahan_sum(xs):
    s = 0.0
    c = 0.0                   # the low-order bits lost so far (negated)
    for x in xs:
        y = x - c             # correct the next term by what was lost
        t = s + y             # big + small: the low bits of y are lost here...
        c = (t - s) - y       # ...and recovered here (algebraically 0)
        s = t
    return s

Adding 0.1 a million times, a plain loop returns 100000.00000133288, about 1.3×10−61.3 \times 10^{-6} off; kahan_sum returns 100000.0, within 6×10−126 \times 10^{-12} of the exact sum of the million stored values. Python's math.fsum returns the correctly rounded sum, and since Python 3.12 the built-in sum of floats is compensated too.

Robust geometry, and bisection on reals

Geometric algorithms make combinatorial decisions from numeric signs. The basic one is the orientation of three points, the sign of

orient⁡(p,q,r)=(qx−px)(ry−py)−(qy−py)(rx−px),\operatorname{orient}(p, q, r) = (q_x - p_x)(r_y - p_y) - (q_y - p_y)(r_x - p_x),

positive for a left turn, negative for a right turn, zero for collinear points. In doubles the sign can be wrong for nearly collinear points. Perturbing (0.5,0.5)(0.5, 0.5), (12,12)(12, 12) and (24,24)(24, 24) by a few units in the last place, 2,280 of 200,000 random triples got a different sign in floating point than in exact arithmetic, for instance 0 instead of a positive value. A convex-hull or triangulation algorithm fed such answers can loop, crash or return a non-convex "hull" (Kettner, Mehlhorn, Pion, Schirra & Yap).

Three remedies, best first:

  • Integers. With integer coordinates of absolute value at most 10910^9, every difference is at most 2×1092 \times 10^9, every product at most 4×10184 \times 10^{18}, and the orientation at most 8×1018<263−1≈9.22×10188 \times 10^{18} < 2^{63} - 1 \approx 9.22 \times 10^{18}: exact in a signed 64-bit integer.
  • Adaptive exact arithmetic. Shewchuk's predicates (1997) evaluate the sign in floating point together with an error bound, and only when the value is too close to zero to trust do they redo the computation exactly. They are about as fast as plain floats on typical inputs, and always right.
  • Tolerances, treating ∣orient⁡∣<ε|\operatorname{orient}| < \varepsilon as zero: easy, but not transitive, so three pairwise decisions can contradict one another.

Binary search on reals has its own trap. The loop while hi - lo > 1e-12 can run forever: near 10910^9 consecutive doubles are 2−23≈1.19×10−72^{-23} \approx 1.19 \times 10^{-7} apart, so once lo and hi are neighbors their midpoint rounds to one of them and the gap never shrinks. Iterate a fixed number of times instead (each step halves the interval, so 100 steps divide it by 2100≈10302^{100} \approx 10^{30}), or stop when the midpoint equals lo or hi. Either way the loop ends.

Predict before you look

Bisection starts on [0,109][0, 10^9]. How many halvings make the interval shorter than 10−610^{-6}?

Show the answer

50

After kk halvings the width is 109/2k10^9/2^k, which drops below 10−610^{-6} once 2k>10152^k > 10^{15}: k=⌈log⁡21015⌉=50k = \lceil \log_2 10^{15} \rceil = 50, since 249≈5.6×10142^{49} \approx 5.6 \times 10^{14} and 250≈1.13×10152^{50} \approx 1.13 \times 10^{15}. A fixed 100 iterations is generous.

Key takeaways

  • Fixed-width integers overflow, and in C and C++ signed overflow is undefined behavior: widen before multiplying, compute midpoints as lo + (hi - lo) / 2, and use 128-bit products for moduli near 101810^{18}.
  • A double has a 53-bit significand, and each operation is correctly rounded with relative error at most u=2−53u = 2^{-53}; but addition is not associative, and subtracting nearly equal numbers cancels the accurate digits.
  • Recursive summation's error grows like (n−1) u∑i∣xi∣(n - 1)\,u\sum_i|x_i|, pairwise summation's like ⌈log⁡2n⌉ u∑i∣xi∣\lceil\log_2 n\rceil\,u\sum_i|x_i|, and Kahan's compensated summation's like 2u∑i∣xi∣2u\sum_i|x_i|.
  • Exact decisions need exact arithmetic, such as integer orientation tests or Shewchuk's adaptive predicates, and bisection on reals should run a fixed number of steps, never "until the gap is below ε\varepsilon".

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Which statement about IEEE double precision is right?

  1. Every decimal number with at most 16 significant digits, such as 0.1, is stored exactly
  2. Each basic operation is correctly rounded, with relative error at most u=2−53u = 2^{-53}, barring overflow and underflow
  3. Floating-point addition is associative
  4. Integers above 2322^{32} cannot be stored exactly
Show the answer

B. Each basic operation is correctly rounded, with relative error at most u=2−53u = 2^{-53}, barring overflow and underflow

IEEE 754 requires ++, −-, ×\times, // and square root to be correctly rounded, so each operation's relative error is at most u=2−53≈1.1×10−16u = 2^{-53} \approx 1.1 \times 10^{-16}. The errors then accumulate across operations, which is what error analysis tracks.

Question 2

What does Kahan's compensated summation keep track of?

  1. The largest term seen so far
  2. The sum of absolute values, to rescale the result
  3. A second, exact copy of the sum in rational arithmetic
  4. The low-order bits lost by each addition, which it feeds back into the next one
Show the answer

D. The low-order bits lost by each addition, which it feeds back into the next one

c = (t - s) - y recovers, exactly in floating point, what the addition t = s + y rounded away, and the next term is corrected by it. That makes the error bound 2u∑i∣xi∣2u\sum_i|x_i| to first order, independent of nn.

Question 3

Why is 109+710^9 + 7 such a popular modulus in programming contests?

  1. It is prime, a sum of two residues fits in a signed 32-bit integer, and a product of two fits in a signed 64-bit integer
  2. It is a power of 2, so reductions are bit masks
  3. Every number below it has an inverse because it is odd
  4. It is the largest prime below 2322^{32}
Show the answer

A. It is prime, a sum of two residues fits in a signed 32-bit integer, and a product of two fits in a signed 64-bit integer

Primality makes every nonzero residue invertible, by Fermat or by extended Euclid; 2(109+7)<231−12(10^9 + 7) < 2^{31} - 1 keeps sums in an int; and (109+7)2≈1018<263−1(10^9 + 7)^2 \approx 10^{18} < 2^{63} - 1 keeps products in a long long.

Question 4

Points have integer coordinates of absolute value at most 10910^9. How should you compute the orientation (qx−px)(ry−py)−(qy−py)(rx−px)(q_x - p_x)(r_y - p_y) - (q_y - p_y)(r_x - p_x)?

  1. In 32-bit integers
  2. In doubles, treating small values as zero
  3. In 64-bit integers: every intermediate value stays below 8×1018<2638 \times 10^{18} < 2^{63}, so the sign is exact
  4. In 32-bit floats
Show the answer

C. In 64-bit integers: every intermediate value stays below 8×1018<2638 \times 10^{18} < 2^{63}, so the sign is exact

Differences are at most 2×1092 \times 10^9, products at most 4×10184 \times 10^{18}, and their difference at most 8×10188 \times 10^{18}, below 263−1≈9.22×10182^{63} - 1 \approx 9.22 \times 10^{18}. Exact integer arithmetic gives the exact sign, with no tolerance to tune.

Further reading

  • D. Goldberg, "What every computer scientist should know about floating-point arithmetic," ACM Computing Surveys 23(1) (1991).
  • N. J. Higham, Accuracy and Stability of Numerical Algorithms, 2nd ed. (SIAM, 2002).
  • W. Kahan, "Further remarks on reducing truncation errors," Communications of the ACM 8(1) (1965).
  • J. R. Shewchuk, "Adaptive precision floating-point arithmetic and fast robust geometric predicates," Discrete & Computational Geometry 18(3) (1997).
  • L. Kettner, K. Mehlhorn, S. Pion, S. Schirra & C. Yap, "Classroom examples of robustness problems in geometric computations," Computational Geometry 40(1) (2008).