The formula appears to demand two passes. We need \(\mu_n\) before we can form the centered deviations. If the stream cannot be revisited, we must either store it or find a different state.
An algebraic identity seems to remove that obstacle:
Now a single pass can carry three scalars: \(n\), \(\sum_i x_i\), and \(\sum_i x_i^2\). The memory problem looks solved.
ImportantPrediction
We will hold the deviations fixed and add the same constant to every value. Exact variance is unchanged by this translation.
Which computation should fail first as the constant grows: the raw-moment formula in Equation 2.2, a centered two-pass calculation, or a centered online calculation? Name the operation that you expect to fail.
2.1 The impossible output
The chapter setup verifies its content-addressed harness once, outside the printed mechanism kernel. The random values are cast to FP32 before the FP64 reference is computed. Every method therefore receives the same represented inputs.
Load the chapter-pinned variance instruments.
Generate one seeded FP32 stream with a large common offset.
Compare three variance methods with a same-input FP64 reference.
Assert the impossible symptom and the centered controls.
The raw-moment estimate is -32, even though the FP64 reference on those same FP32 values is 1.002515. The population denominator is not the culprit: changing \(n\) to \(n-1\) would rescale an already corrupted centered sum. Random sampling is not the culprit either: sampling can move a variance away from one, but not below zero.
The impossible answer is not an arbitrary negative number. The two rounded terms are 400000192 and 400000224; their local grid spacing is \(\operatorname{ulp}(\mu^2)=\) 32. The result therefore lands one grid step below zero: \(-\operatorname{ulp}(\mu^2)=\) -32. The scale model in Equation 2.3 predicts roughly 23.8; it locates the grid scale without pretending to predict a particular reduction path exactly.
The common offset is about 19,975 reference standard deviations. That ratio points toward the dangerous subtraction.
The shift test
Use the same deviations at every offset. This removes a tempting alternate explanation: changes in the graph cannot be attributed to a new random sample.
Hold one random deviation vector fixed.
Add offsets without changing the exact centered variance.
Evaluate all methods on the same represented inputs.
Plot relative error and mark impossible negative results.
Figure 2.1: The raw-moment formula degrades as a common offset grows, although exact variance is translation invariant. Downward triangles mark negative estimates. Centered methods avoid the dominant cancellation, but the figure does not claim that they eliminate all rounding or input-quantization error.
The relevant observation is not that one curve has a particular shape. It is that a transformation which preserves exact variance changes the raw-moment answer dramatically. The experiment has isolated sensitivity to translation.
The raw-moment formula asks floating-point arithmetic to construct two values on the scale of \(\mu^2\), then subtract them to recover one on the scale of \(\sigma^2\).
Suppose, as a diagnostic model calculation, that the two large terms acquire absolute errors of order \(u\mu^2\), where \(u\) is the unit roundoff. The absolute error in their difference is then also on that scale. Relative to the desired variance, the amplification is approximately
This is not a complete forward-error bound for a particular summation kernel. It deliberately suppresses the number of additions, reduction order, compensation, and intermediate precision. It does explain the observed control: translating the data leaves exact variance alone while increasing the scale of the two terms that must cancel.
WarningNamed wrong answer: ‘FP32 cannot represent the noise’
At the opening offset, FP32 still represents many distinct unit-scale deviations. We know because the FP64 reference is computed after the FP32 cast and remains near one. The dominant opening failure is algorithmic cancellation, not already-lost input information.
At a sufficiently larger offset, the spacing between representable FP32 values does become comparable with the deviations. That is a different failure, and no variance algorithm can recover distinctions absent from its input.
The two failures must stay separate:
Failure
Where information is lost
Can centered state repair it?
Raw-moment cancellation
During accumulation and subtraction of large moments
It avoids the dominant subtraction
Input quantization
When real values are rounded to the input dtype
No; the distinctions never reach the algorithm
The next chapter develops the precision language needed to quantify the second row. For now, this separation is enough to design the state.
The final population variance is \(M_{2,n}/n\). The usual unbiased sample variance is \(M_{2,n}/(n-1)\) when \(n>1\). The state does not need to commit to either denominator while the stream is arriving.
When \(x_n\) arrives, define its deviation from the old mean:
\[
\delta_n:=x_n-\mu_{n-1}.
\]
The mean update follows directly from the definition:
which is exactly the increment added by the centered-sum update. \(\square\)
The proof does more than validate a formula. It identifies the invariant the state represents after every prefix. That invariant lets us test the kernel on any prefix and gives us the object that partial computations must preserve.
The mechanism in code
Initialize the empty centered state.
Update the mean with the deviation from the old mean.
Update the centered sum using deviations from both means.
Check the kernel against the pinned harness and a direct calculation.
The update remains a floating-point recurrence. Centering removes the particular subtraction diagnosed by Equation 2.3; it does not make every update exact. “Stable” always needs an object and a failure mode. Here it means that the algorithm avoids forming raw moments on the scale of \(\mu^2\) merely to recover a centered quantity on the scale of \(\sigma^2\).
2.4 One state must also combine
Sequential state solves the one-pass problem for one stream. It does not yet solve the execution problem for many blocks. If block \(A\) and block \(B\) are processed independently, each produces a valid state:
Theorem 2.2 (Pairwise centered-state merge) If \(h_A\) and \(h_B\) satisfy the centered-state invariant on disjoint collections \(A\) and \(B\), then Equation 2.7 and Equation 2.8 satisfy it on \(A\cup B\).
In exact arithmetic, the merge operation is associative on valid states. A state represents the count, mean, and centered sum of squares of one underlying multiset. Both
represent the same union, whose three exact statistics are unique.
That statement gives us a parallel reduction tree. It does not say that floating-point parenthesizations are bitwise identical. Each merge rounds, so the tree becomes part of the numerical algorithm.
Form the same FP32 block states once.
Merge them left-to-right, right-to-left, and in a balanced tree.
Retain a sequential state and same-input FP64 reference as controls.
Report the spread without declaring one order universally best.
# [1]order_rng = np.random.default_rng(6211)order_values = (20_000.0+ order_rng.normal(size=131_072)).astype(np.float32)blocks = [ stable_online_moments(block, dtype=np.float32)for block in np.array_split(order_values, 128)]def left_fold(states): state = states[0]for next_state in states[1:]: state = merge_moments(state, next_state)return statedef balanced_fold(states): level =list(states)whilelen(level) >1: level = [ merge_moments(level[index], level[index +1])if index +1<len(level)else level[index]for index inrange(0, len(level), 2) ]return level[0]# [2]orders = {"left": left_fold(blocks),"right": left_fold(list(reversed(blocks))),"balanced": balanced_fold(blocks),}# [3]orders["sequential"] = stable_online_moments(order_values, dtype=np.float32)order_reference =float(np.var(order_values.astype(np.float64)))# [4]for name, state in orders.items():print(f"{name:>10}: variance={state.population_variance:.9f}, "f"error={abs(state.population_variance - order_reference):.3e}" )print(f"{'reference':>10}: variance={order_reference:.9f}")
The three merge trees differ in their final bits, as expected. The balanced tree is not promoted here as a universal accuracy theorem: data order, partial-state quality, accumulator width, and the implementation of the combine all matter. The supported claim is narrower. A mathematical combine law creates parallel structure; floating-point execution still requires a reduction-order audit.
2.5 Choosing the state is choosing the algorithm
The original question was not “which variance formula should a library use?” The useful question is “what constraints does this execution have?”
Constraint
Honest baseline
Principal cost or boundary
Data can be revisited
Centered two-pass variance
Reads the input at least twice
True one-pass stream
Sequential centered state
Dependency depth grows with stream length
Independent blocks
Centered partial states plus pairwise merge
Floating-point tree order affects final bits
Input distinctions already lost
Wider storage or an upstream scaling change
No downstream state can reconstruct missing values
The raw-moment formula remains an algebraic identity. Its failure does not make the identity false. It makes the evaluation path unsuitable in the observed regime.
The same centered state later appears inside batch-coordinate normalization: its running statistics are mergeable estimates whose axes, denominator, update rule, and accumulator precision must be declared explicitly.
NoteField note: what a trace can and cannot tell you
A negative variance strongly implicates numerical execution because exact variance is nonnegative. A merely inaccurate positive variance is less diagnostic. It can come from cancellation, input quantization, accumulation order, a mismatched denominator, or a changing target. Record the state, dtype, axes, denominator, and same-input reference before assigning a cause.
TipCheck yourself
You have two blocks whose internal variances are both zero, but whose means differ. Why is adding the two \(M_2\) values wrong? Which single term repairs the result, and what does that term measure?
2.6 Okay, so —
Inherited: A formula has a data-movement schedule; rereading a tensor is an algorithmic decision.
Changed: Variance is no longer just a definition. It is a state-design problem constrained by passes, rounding, and parallel structure.
Instrumented: The harness now records the execution contract, compares methods on the same represented inputs, maintains centered moments, and merges partial states.
Established: The centered online recurrence and the pairwise correction preserve \(M_2\) in exact arithmetic. The seeded FP32 witness establishes that the raw-moment evaluation can return an impossible negative result.
Unresolved: Which precision contract separates values lost at storage from errors introduced by a non-associative reduction?
2.7 Sources and further reading
The corrected online update traces to Welford’s short note (Welford 1962). Chan, Golub, and LeVeque compare variance algorithms, analyze roundoff, and develop pairwise computation (Chan et al. 1983).
Hennig, Pförtner, and Weiland frame limited computation as limited information (Hennig et al. 2026). Hennig makes one version exact for iterative linear solvers under a declared Gaussian model (Hennig 2015). That work motivates Exercise 7; it does not make the centered-moment recurrence a Bayesian update.
For floating-point format anatomy, mixed-precision roles, and introductory rounding examples, see the sibling volume’s precision and hardware appendix. This chapter instead owns the centered invariant, merge law, and same-input diagnostic.
Reading order. Start with Welford (1962) for the recurrence and Chan et al. (1983) for the stability and merge analysis; read Hennig (2015) only after the chapter’s state-versus-belief boundary is clear.
2.8 Exercises
(Pencil.) The invariant from another direction. Starting from \(M_{2,n}=\sum_{i=1}^{n}x_i^2-n\mu_n^2\), derive the centered-sum update stated in this chapter. Mark the step that is safe as an exact identity but would reintroduce the raw-moment hazard if used as the implementation.
(Pencil.) Population versus sample. Prove that the same state \((n,\mu_n,M_{2,n})\) can produce either the population variance or the usual unbiased sample variance. Explain why changing the final denominator cannot repair catastrophic cancellation already present in \(M_{2,n}\).
(Code.) Crash map. Hold one represented deviation vector fixed and sweep both offset and accumulator dtype. Report the first offset at which the raw-moment estimate becomes negative and the first at which the centered methods exceed one percent relative error. Keep the FP64 reference on the same represented inputs.
(Code.) Profile: one pass versus two. On a laptop CPU, compare bytes implied by one-pass and two-pass schedules for a contiguous FP32 array. Time the implementations only after stating warmup, sample count, and estimator. Do not interpret CPU timing as accelerator performance.
(Audit.) The clipped repair. A code review proposes variance = max(raw_variance, 0). Predict which visible symptom this removes, then design a test showing what error it conceals. State the strongest claim the clipped result can support.
(Audit.) Merge contract. An implementation all-reduces only \((n,\mu,M_2)\) by componentwise sum. Use two constant blocks to identify the defect. Write the missing correction and explain why the tempting componentwise answer is wrong.
(Audit.) Paper audit: state versus belief. Complete the Mathematical object, Evidence culture and interface, Estimator and comparison contract, Assumption stress test, and Transfer verdict fields for Hennig’s Gaussian linear-solver construction (Hennig 2015). Compare its state \((\vect{\mu}_i,\matr{\Sigma}_i)\) with Welford’s \((n,\mu_n,M_{2,n})\): record the target, observation, prior, rank-one update, stopping output, and uncertainty claim. Identify the shared state-machine pattern, then explain why Welford is not Bayesian conditioning without an additional probability model.
Chan, Tony F., Gene H. Golub, and Randall J. LeVeque. 1983. “Algorithms for Computing the Sample Variance: Analysis and Recommendations.”The American Statistician 37 (3): 242–47. https://doi.org/10.1080/00031305.1983.10483115.
Hennig, Philipp. 2015. “Probabilistic Interpretation of Linear Solvers.”SIAM Journal on Optimization 25 (1): 234–60. https://doi.org/10.1137/140955501.
Hennig, Philipp, Marvin Pförtner, and Tim Weiland. 2026. Probabilistic Numerics: Computation Is Machine Learning. Tutorial at the 43rd International Conference on Machine Learning. https://icml.cc/Downloads/2026.