Streaming mean and variance (Welford)
Problem
Process stream in one pass with O(1) state. After each element, output (mean, population_variance) of the elements seen so far, staying accurate for values around 1e9.
Signature
def streaming_stats(stream: list[float]) -> list[tuple[float, float]]: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> close(streaming_stats([2.0, 4.0, 6.0]), [(2.0, 0.0), (3.0, 1.0), (4.0, 2.666667)])
True
>>> streaming_stats([]) == []
TrueHints
Use Welford: delta = x - mean; mean += delta/n; M2 += delta * (x - mean).
Population variance = M2/n; output after every element.
Avoid the naive sum-of-squares formula — it loses precision around 1e9.
Reference solution
def streaming_stats(stream):
n = 0; mean = 0.0; m2 = 0.0; out = []
for x in stream:
n += 1
d = x - mean
mean += d / n
m2 += d * (x - mean)
out.append((mean, m2 / n))
return outWhat a strong solution covers
- Welford update (
delta,mean += delta/n,M2 += delta·(x − mean)). - Explains catastrophic cancellation in the naive Σx²/n − mean² approach.
- Merging two partial aggregates (parallel or Chan’s formula).
- Sample vs population variance.
Common mistakes
- the naive sum-of-squares formula losing precision at 1e9
- integer division in other languages.