Quant interview toolkit · numerical statistics

A one-pass variance you can merge across machines

Four consecutive observations are a trillion plus 1, 2, 3 and 4. Their mean is a trillion plus 2.5. Their deviations are small enough to square in your head. Yet a program that computes mean square minus squared mean can report zero variance. The data fit in memory here. On a feed with billions of observations, how do you keep the same arithmetic reliable in one pass?

Merge two groups without raw observations

Combined population variance

Two equal-sized groups each with variance 1; first mean 0, second mean x. Between-group variance adds x²/4.

Center the quantity you accumulate

Let MnM_n be the running mean and Qn=∑i=1n(xi−Mn)2Q_n=\sum_{i=1}^n(x_i-M_n)^2 the running sum of squared deviations. For a fresh observation xx, set δ=x−Mn\delta=x-M_n. The mean moves by δ/(n+1)\delta/(n+1).

Shifting the center of the old observations increases their squared-deviation sum by n(Mn+1−Mn)2n(M_{n+1}-M_n)^2. The cross term vanishes because the old deviations sum to zero. Then add the new observation’s own squared deviation. Combining the terms gives

Qn+1=Qn+nn+1δ2=Qn+(x−Mn)(x−Mn+1).Q_{n+1}=Q_n+\frac{n}{n+1}\delta^2 =Q_n+(x-M_n)(x-M_{n+1}).

The second form is Welford’s update. The two factors straddle the mean update, so preserve the old difference before overwriting the mean. Divide QnQ_n by nn for the variance of the observed population or by n−1n-1 for the usual sample variance.

def summarize(values):
    count, mean, squared = 0, 0.0, 0.0
    for value in values:
        count += 1
        delta = value - mean
        mean += delta / count
        squared += delta * (value - mean)
    return count, mean, squared

values = [10**12 + j for j in (1, 2, 3, 4)]
n, mean, squared = summarize(values)
print(squared / n, squared / (n - 1))  # 1.25, 1.666...

The true raw second moment and squared mean are both about 102410^{24}. Nearby binary64 numbers at that scale are spaced more than a hundred million units apart. A difference of 1.25 can disappear before the subtraction happens. Working with deviations also has limits. If incoming values have already rounded to the same floating-point number, a later centering operation cannot reconstruct the lost variation.

What gets lost when shards send only a variance?

Server A sees 1 and 3. Server B sees 7 and 9. Each server has population variance 1. Pooling the four observations gives mean 5 and population variance 10. Averaging the local variances accounts only for dispersion around each local mean. It misses the separation between means 2 and 8.

Suppose each server sends its count nn, mean MM, and centered sum QQ. For two nonempty groups write d=MB−MAd=M_B-M_A and n=nA+nBn=n_A+n_B. The pooled summary is

M=MA+dnBn,Q=QA+QB+d2nAnBn.M=M_A+d\frac{n_B}{n},\qquad Q=Q_A+Q_B+d^2\frac{n_A n_B}{n}.

To derive the extra term, move each group’s center to the pooled mean. Its increase in squared deviation is its count times the squared distance its center moved. In the example the correction is 62(2)(2)/4=366^2(2)(2)/4=36. Each local centered sum is 2, giving Q=40Q=40 and population variance 40/4=1040/4=10. A singleton group with QB=0Q_B=0 recovers the one-observation update.

Decide which observations are allowed into the summary

If the feed can carry missing or nonfinite measurements, decide their treatment before updating any of the three fields. Skipping a missing measurement requires skipping its count as well. Define the empty summary as count zero and centered sum zero. Its mean is just a placeholder. Merging it with a populated group should return the populated summary directly. Reporting sample variance requires at least two observations.

The merge formula describes disjoint groups. Replaying the same shard twice counts its observations twice. Floating-point implementations can also differ slightly across merge orders, even with identical records and correct algebra. Compare results to a centered two-pass reference with a numerical tolerance.

Practice

Hand checkStarting with observations 1 and 3, add 8. How large is the centered sum now?
Show answer

The old mean is 2 and the old centered sum is 2. The new mean is 4, so the update adds (8−2)(8−4)=24(8-2)(8-4)=24. Directly, the new deviations are −3,−1,4-3,-1,4, whose squares sum to 26.

Missing fieldTwo shards transmit their counts and means, but neither sends a centered sum. Can the pooled variance be recovered?
Show answer

The counts and means determine the between-group correction. They leave the within-group contributions unknown. For example, a two-record shard with mean 2 could contain 2 and 2 or 1 and 3. Its contribution to the pooled centered sum differs by 2.