Variance from raw sums of squares loses all its digits when the mean is large
Symptom#
std and var are wrong for data with a large mean and a small spread. For 1e9 + N(0,1), a series std gave 0.0 and a grouped std gave 152.38, where numpy and pandas give 1.000672337. For values of 1e3 ± 1e-3 the relative error was 6.3e-4.
Cause#
The accumulator kept the raw sums sum x and sum x^2 and computed the variance as sumsq - sum^2 / n. The two terms are almost equal when the mean is large, so the subtraction cancels the significant digits.
Fix#
Keep central moments, not raw power sums:
- Keep a running mean and the sum of squared deviations, with Welford updates.
- Merge partial states (partitions, groups, distributed workers) with the Chan merge of count, mean and squared deviations.
- A mean held in one
doublewas not accurate enough for merges: the error was 2.9e-9 at mean 1e9 and 1.7e-4 at mean 6e11. Hold the mean as a pair (a shift plus a small remainder). - Check every reader of the stored second moment. A reader that still treats it as a raw sum is now wrong.
- Covariance and correlation from raw co-moment sums have the same flaw.
Evidence#
Seen in dftracer-utils on 2026-10-01. After the fix, 1e9 + N(0,1) gave 1.000672337 for the series and the grouped std, and the relative error for 1e3 ± 1e-3 went to about 1e-15. A constant column gives variance 0.0. The tests compare against numpy within 1e-9. The cost over 5 million values: a series std went from 0.3 ms to 0.6 ms, and a one-group grouped std from 10.7 ms to 19.8 ms. Before the fix for correlation, Series.corr gave 0.0 where pandas gave 0.4477.