Track mean and variance of a stream in one pass

Batch norm, Adam and monitoring dashboards all keep running statistics over a stream that never fits in memory. The naive formula mean(x ** 2) - mean(x) ** 2 loses precision badly. Welford's method updates the mean and the sum of squared deviations one value at a time.

Write running_stats(values) that walks the values once and returns (mean, variance), where variance is the population variance (divide by n). For an empty list return (0.0, 0.0).

Signaturedef running_stats(values)

Understand the idea

Welford's method keeps a running mean and a running sum of squared deviations, updating both with each new value. You never store the whole stream, and you avoid the formula mean(x^2) - mean(x)^2, which subtracts two huge nearly equal numbers and loses precision. Think of a teacher updating the class average as each new mark arrives. Worked example: values [2, 4, 6]. After 2: n = 1, mean = 2, M2 = 0. After 4: delta = 4 - 2 = 2, mean = 3, M2 += 2 * (4 - 3) = 2. After 6: delta = 6 - 3 = 3, mean = 4, M2 += 3 * (6 - 4) = 6, so M2 = 8. Population variance = 8 / 3 = 2.667. Check: deviations -2, 0, 2 squared sum to 8. Rule: n += 1; delta = x - mean; mean += delta / n; M2 += delta * (x - new mean); variance = M2 / n. Empty input gives (0.0, 0.0). Batch norm statistics and metric dashboards use running updates like this.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: small listrunning_stats([2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0])
  • Sample 2: huge offset stays preciserunning_stats([1e9 + 4.0, 1e9 + 7.0, 1e9 + 13.0, 1e9 + 16.0])
  • Test 3: emptyrunning_stats([])
  • Test 4: one valuerunning_stats([3.5])