Floating point: IEEE 754, cancellation and why prices are integers
NUM · Chapter 611 min readAsked at Hudson River Trading, Jump, Optiver, IMC
Assumes ODE and PDE solvers: finite differences and stability.
After this lesson you should be able to
- Say what a double can and cannot represent exactly.
- Recognise catastrophic cancellation and restructure to avoid it.
- Explain why exchanges store prices as integers.
Floating point is an approximation that is almost always good enough and occasionally catastrophic. The failures are not random — they happen at predictable places, and knowing those places is the difference between code that is correct and code that has not been tested at the boundary yet.
Proposition 6.1
What a double holds
A 64-bit double has one sign bit, eleven exponent bits and fifty-two mantissa bits, giving about sixteen significant decimal digits. The spacing between representable numbers scales with magnitude, so precision is *relative*: near 1 the gap is about , and near it is about .
Holds when
- Integers are exact up to , which is about .
- Decimal fractions like have no exact binary representation, in the same way has no exact decimal one.
- Never test floats for equality — compare against a tolerance scaled to the magnitude.
Catastrophic cancellation. Subtracting two nearly equal numbers destroys precision in a way that nothing later recovers. Each input carries sixteen good digits; if the first eight agree, they cancel and the result has eight good digits — but it is stored in a double that looks just as precise as before, so the loss is invisible. Everything downstream then inherits an error the code gives no sign of. This is why computing a variance as can return a small negative number: two large nearly equal quantities were subtracted, and the true answer was smaller than the error.
Example 6.2
Compute the variance of a million prices near with a true standard deviation of , using . What goes wrong?
Show the worked solutionHide the worked solution
Worked solution
- Formula
- Substitute
- Solve
- Answer
Sanity check. Move the prices to and there is nothing left at all. Welford’s algorithm updates the mean and the sum of squared deviations incrementally and never forms the difference, so it stays accurate regardless of the offset.
The rest of this lesson is in Premium
You have read the opening. 11 more sections follow, including 3 worked examples and 3 quick checks.
Nothing is charged for 7 days, and you can cancel before then. Or read Complexity: reading it off, and deriving it in full, free.