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 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 . Unsigned ones live in and their arithmetic wraps around modulo ; signed ones use two's complement, with range . A 32-bit int ends at , just over : three values of already overflow when added, and 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.
#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 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: . Moduli near need 128-bit products.
In C++, int a = 50000, b = 50000; long long c = a * b; What does c hold?
- 2,500,000,000, because
cis along long - Nothing defined:
a * bis computed as anintand overflows before the conversion, which is undefined behavior (in practice usually ) - 0
- 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 )
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: . Every integer up to is exact, but is not representable. Each basic operation is computed exactly and then rounded to the nearest double, which gives the standard model of rounding error:
for , barring overflow and underflow. The unit roundoff is half of machine epsilon, , the gap between 1 and the next double.
| Expression | In doubles | Why |
|---|---|---|
0.1 + 0.2 == 0.3 | False: the sum is 0.30000000000000004 | 0.1, 0.2 and 0.3 are not representable, and the rounding errors do not cancel |
(1e16 + 1) - 1e16 | 0.0, while (1e16 - 1e16) + 1 is 1.0 | near consecutive doubles are 2 apart, so the 1 is rounded away: addition is not associative |
(1 - cos(x)) / x**2 at x = 1e-8 | 0.0 instead of | rounds to exactly 1, and subtracting nearly equal numbers, cancellation, exposes the earlier rounding |
2 * sin(x/2)**2 / x**2 gives 0.5. Stable formulas avoid subtracting nearly equal computed quantities.Summing many numbers
Adding numbers one after another, recursive summation, makes roundings, each up to times a partial sum. To first order in the error obeys
Adding in a balanced binary tree, pairwise summation, sends each through only additions, and the factor becomes . 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.
One rounding per addition. Let and . By the standard model,
Unroll. Each is rounded again by every later addition: and by additions , and by additions . So
Bound the products. A product of factors with and equals with , and every carries at most factors:
Pairwise summation sends each through at most additions, so the same argument gives instead of . 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.
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 sAdding 0.1 a million times, a plain loop returns 100000.00000133288, about off; kahan_sum returns 100000.0, within 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
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 , and 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 , every difference is at most , every product at most , and the orientation at most : 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 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 consecutive doubles are 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 ), or stop when the midpoint equals lo or hi. Either way the loop ends.
Bisection starts on . How many halvings make the interval shorter than ?
Show the answer
50
After halvings the width is , which drops below once : , since and . 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 . - A double has a 53-bit significand, and each operation is correctly rounded with relative error at most ; but addition is not associative, and subtracting nearly equal numbers cancels the accurate digits.
- Recursive summation's error grows like , pairwise summation's like , and Kahan's compensated summation's like .
- 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 ".
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Which statement about IEEE double precision is right?
- Every decimal number with at most 16 significant digits, such as 0.1, is stored exactly
- Each basic operation is correctly rounded, with relative error at most , barring overflow and underflow
- Floating-point addition is associative
- Integers above cannot be stored exactly
Show the answer
B. Each basic operation is correctly rounded, with relative error at most , barring overflow and underflow
IEEE 754 requires , , , and square root to be correctly rounded, so each operation's relative error is at most . The errors then accumulate across operations, which is what error analysis tracks.
What does Kahan's compensated summation keep track of?
- The largest term seen so far
- The sum of absolute values, to rescale the result
- A second, exact copy of the sum in rational arithmetic
- 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 to first order, independent of .
Why is such a popular modulus in programming contests?
- 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
- It is a power of 2, so reductions are bit masks
- Every number below it has an inverse because it is odd
- It is the largest prime below
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; keeps sums in an int; and keeps products in a long long.
Points have integer coordinates of absolute value at most . How should you compute the orientation ?
- In 32-bit integers
- In doubles, treating small values as zero
- In 64-bit integers: every intermediate value stays below , so the sign is exact
- In 32-bit floats
Show the answer
C. In 64-bit integers: every intermediate value stays below , so the sign is exact
Differences are at most , products at most , and their difference at most , below . 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).