Numerical computing · Worked lesson
When correct formulas give wrong answers
Before you start: Know how to find a mean and square a difference. You can follow the arithmetic without running code.
The question
Four readings taken from a counter are 1,000,000,000; 1,000,000,001; 1,000,000,002; and 1,000,000,003. The spread is small, but not zero. Can the way you calculate it erase the spread?
Model the quantities before calculating
A floating-point value has a limited number of significant bits. In binary64, the usual 64-bit floating-point format used for JavaScript numbers, nearby representable numbers are more widely spaced at large magnitudes. At about one billion, the four integer readings themselves are exactly representable. Squaring them brings them to about one quintillion, where finer differences can be lost when the products and sums are rounded. Printing more decimal places afterward cannot recover those bits.
In exact arithmetic, population variance can be computed as the mean of the squares minus the square of the mean. The algebra is correct. The direct calculation can nevertheless subtract two enormous, separately rounded results and lose the small variance between them. This is cancellation: the shared leading digits cancel, leaving the earlier rounding errors large relative to the result.
Worked example: center, then square
Treat the four readings as the entire population for this exercise. Their mean is 1,000,000,001.5. Subtract it before squaring. The deviations are −1.5, −0.5, +0.5 and +1.5. The sum of their squares is 5. Divide by 4 to get population variance 1.25 squared units. If these four readings were treated as a sample and you were estimating population variance with the usual corrected estimator, divide by 3 instead; that is a different statistical choice, not a numerical fix.
In a simple JavaScript binary64 calculation, evaluating the raw-moment formula with left-to-right sums gives 0 for this dataset; the centered calculation gives 1.25. Other operation orders need not produce the same erroneous number. For this dataset you can also subtract the first reading and use the small offsets 0, 1, 2, 3. Subtracting the same constant from every reading moves the mean without changing variance. Centering cannot recover differences already missing from the inputs.
const readings = [1000000000, 1000000001, 1000000002, 1000000003];
const n = readings.length;
const mean = readings.reduce((total, x) => total + x, 0) / n;
const populationVariance =
readings.reduce((total, x) => total + (x - mean) ** 2, 0) / n;
const meanSquare = readings.reduce((total, x) => total + x * x, 0) / n;
console.log({ raw: meanSquare - mean * mean, centered: populationVariance });
// { raw: 0, centered: 1.25 }This example uses a second pass over stored readings. If readings arrive in a stream and cannot be replayed, use an established running mean and centered sum-of-squares method rather than tracking the two raw moments and subtracting. For extreme magnitudes, also check for overflow; the two-pass example is not a guarantee for every range.
Decide how to represent the number
Choose an exact decimal type or integer minor units for transactions when the unit and rounding rules are known, and check range before accumulating. Choose centered arithmetic for a spread around a large baseline. For reporting small percentage changes, preserve the baseline and absolute change as separate data fields when possible; a display rounded to two decimals can read “0.00%” without the actual change being zero.
Try it
- Subtract one billion from each reading. Predict which result should stay the same. Run both calculations again and see which one changes.
- Compare a change from 1,000,000,000 to 1,000,000,003. Report the absolute change and relative change before rounding for display.
- Three receipts under a two-decimal currency are 1,000.03, 1,000.01 and 1,000.02. Sum them using integer minor units. Does adding them this way settle when tax should be rounded?
Check your answers
- The centered variance remains 1.25 because the shift cancels in each deviation. The raw calculation changes from 0 to 1.25; a check for nonnegative output alone would not catch that error.
- Three units and 0.000000003 relative change, or 0.0000003%.
- 100,003 + 100,001 + 100,002 = 300,006 minor units, or 3,000.06. No: when and how to round tax is a separate rule.
Glossary
- Precision
- resolution of a numerical representation.
- Rounding
- mapping a result to a representable value.
- Cancellation
- loss of relative accuracy when nearly equal quantities are subtracted.
- Centered calculation
- operates on differences from a reference or mean.
- Numerical stability
- how well a method controls computational rounding error, distinct from sensitivity of the underlying problem to input changes.