KatInterview

Calculate Population Variance Using Welford's Method

Math & Bit ManipulationAuto-graded · 23 test cases
EasyAuto-gradedMath & Bit Manipulationmathstatisticsnumerical-stability

Last updated

Tests ability to implement numerically stable variance computation with single-pass streaming aggregation and handling of floating-point precision issues.

Write a function that computes the population variance of a list of numbers.

You are given a list of numeric values (integers or floats) with at least one element. Your task is to calculate the population variance, defined as:

$$\text{variance} = \frac{1}{n}\sum_{i=1}^n (x_i - \mu)^2$$

where $\mu$ is the mean of all values and $n$ is the total count.

Important: Implement a numerically stable algorithm suitable for streaming data. The naive formula $E[X^2] - (E[X])^2$ suffers from catastrophic cancellation when values are large and similar, potentially producing negative results due to floating-point errors. Use an incremental approach that maintains numerical stability.

Your solution should:

  • Process the data in a single pass
  • Use constant extra space
  • Handle edge cases correctly (single element should return 0.0)
  • Work with both integer and floating-point inputs

Constraints

  • $1 \leq n \leq 10^5$ where $n$ is the length of the input list
  • All values fit within standard Python float range
  • Population variance is guaranteed to be non-negative for valid inputs

Examples

Example 1

Input: compute_variance([1, 2, 3, 4, 5])

Output: 2

Example 2

Input: compute_variance([1.5, 2.5, 3.5])

Output: 0.6666666666666666

Example 3

Input: compute_variance([7])

Output: 0

Hints

Hint 1

Welford's online algorithm maintains a running mean and running sum of squared deviations, updating both incrementally as each element is processed.

Hint 2

For each new value, compute its deviation from the current mean, update the mean, then update the sum of squared deviations using both the old and new deviation.

Hint 3

The update formula for squared deviations is: M2 += (value - old_mean) * (value - new_mean), which avoids forming large intermediate values.