Floating-point error in engineering calculations
Why the one-pass variance formula fails, and the algorithms statistical software should use instead.
Engineering software runs on floating-point arithmetic, and floating-point numbers are not real numbers. Most of the time the difference is invisible. Occasionally it produces a standard deviation of zero, a negative variance, or a Cpk that changes in the third digit when the data is merely shifted. Knowing where the errors come from makes them easy to avoid.
What a double can hold
An IEEE 754 double-precision number stores a 53-bit significand, which gives about 15 to 16 significant decimal digits. The gap between 1.0 and the next representable number, machine epsilon, is:
Every arithmetic result is rounded to the nearest representable value, so each operation can introduce a relative error of about . Values like 0.1 can't be represented exactly in binary at all, which is why 0.1 + 0.2 == 0.3 is false in most languages.
Catastrophic cancellation
Subtracting two nearly equal numbers keeps their absolute error but destroys their leading digits. The relative error of the result can be enormous. The textbook example is the "one-pass" variance formula:
For shaft diameters such as 25.0013, 25.0021 and 25.0008 mm, both terms in the numerator are about 1,875 and agree in their first ten digits. The difference that matters lives in the last few digits, exactly where rounding error sits. The result can be badly wrong and can even come out negative.
Welford's algorithm
A stable alternative updates the mean and the sum of squared deviations one value at a time:
and the variance is . Because it works with deviations from the running mean, it never subtracts two large, nearly equal totals. A two-pass method (compute the mean first, then sum squared deviations) is equally accurate when all the data fits in memory.
Other habits that prevent trouble
- Center the data before regression or polynomial fitting. Subtract the mean of so the normal equations aren't ill-conditioned.
- Don't test floats for equality. Compare with a tolerance scaled to the magnitude of the values.
- Sum small values first, or use compensated (Kahan) summation for long series.
- Use library routines for special functions such as the normal CDF and its inverse. Naive formulas lose accuracy in the tails, which is exactly where PPM estimates live.