---
title: Streaming mean and variance (Welford)
url: https://gurkanozkan.ai/learn/coding/mle-streaming-mean-and-variance-welford-26/
markdown: https://gurkanozkan.ai/learn/coding/mle-streaming-mean-and-variance-welford-26.md
kind: coding
difficulty: Easy
topics:
  - Streaming
  - Numerical stability
  - Statistics
json: https://gurkanozkan.ai/api/learn/coding/mle-streaming-mean-and-variance-welford-26.json
robots: noindex
---

# Streaming mean and variance (Welford)

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

```python
def streaming_stats(stream: list[float]) -> list[tuple[float, float]]: ...
```

## Examples

Each call and the value it should give.

```python
>>> 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
```

## Hints

1. Use Welford: delta = x - mean; mean += delta/n; M2 += delta * (x - mean).
2. Population variance = M2/n; output after every element.
3. Avoid the naive sum-of-squares formula — it loses precision around 1e9.

## Reference solution

```python
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.*
