LearnCoding

Streaming mean and variance (Welford)

EasyStreaming, Numerical stability, Statistics

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([]) == []
True

Solve it in your own editor; nothing on this page runs code.

Hints

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 out

What 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.

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.