Each server could send its count, sum and sum of squares, and the coordinator could use Σx² − (Σx)²/n. Chan, Golub and LeVeque warned that computing a variance can be difficult when N is large and the variance is small. Try order timestamps:
Predict
1,000 order times in milliseconds sit near 1.76 trillion and spread over one second. What does Σx² − (Σx)²/n give for the variance?
def summarize(x): return len(x), x.mean(), ((x - x.mean()) ** 2).sum()def merge(a, b): na, ma, sa = a nb, mb, sb = b n, d = na + nb, mb - ma return n, ma + d * nb / n, sa + sb + d * d * na * nb / n# order times in ms, all in one secondstamps = [1_763_512_345_678 + rng.integers(0, 1_000, 100) for _ in range(10)]k = sum(len(s) for s in stamps)s1 = sum(float(s.sum()) for s in stamps)s2 = sum(float((s.astype(float) ** 2).sum()) for s in stamps)naive = (s2 - s1 * s1 / k) / (k - 1)t = summarize(stamps[0].astype(float))for s in stamps[1:]: t = merge(t, summarize(s.astype(float)))print(f"from sums of squares: {naive:,.0f}")print(f"from merged summaries: {t[2] / (t[0] - 1):,.0f}")
from sums of squares: -550,306,120from merged summaries: 80,723
A negative variance. John D. Cook warns that the loss of precision can be so bad that the textbook formula evaluates to a negative number. The merged summaries subtract each server's mean before squaring, so they never hold a huge number. The Praat manual notes the same about the pairwise version of this merge: combining in pairs means fewer operations, and so less rounding noise.
In the editor, write mean_and_variance(summaries). It prints two servers whose orders are all $20 and all $80: the mean, and a variance that is all gap between the means.
Pick an answer above to see the rest
Instructions
1
Write mean_and_variance(summaries): merge every server's (n, mean, m2) with merge, then return the overall mean and the sample variance, m2 / (n − 1).