Calculate Population Variance Using Welford's Method
Math & Bit ManipulationAuto-graded · 23 test casesLast 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.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The challenge is to compute variance accurately while avoiding numerical instability. We use Welford's online algorithm, which incrementally maintains three values as we scan through the data:
- count: number of elements processed so far
- mean: running average of elements seen
- squared_deviations: cumulative sum of squared differences from the running mean
For each incoming value, we:
- Calculate its deviation from the current mean
- Update the mean by adding
deviation / count - Update the squared deviations using
old_deviation * new_deviation
The key insight is that by centering deviations around a running mean (rather than computing large squares and subtracting them), we keep intermediate values small even when the data values themselves are very large. This prevents the catastrophic cancellation that occurs in the textbook formula $E[X^2] - (E[X])^2$.
Why This Works
The mean update is straightforward: incorporating a new value into an average is equivalent to adding the difference between that value and the current average, divided by the new count.
For the squared deviations, the mathematical justification relies on the fact that when we shift the center point (mean) slightly, the sum of squared deviations from the new center can be expressed in terms of the old sum plus a correction term. The correction for the new value is exactly (value - old_mean) * (value - new_mean).
This formulation ensures that:
- All arithmetic operates on deviations (small numbers) rather than raw values (potentially large)
- The sum of squared deviations only increases, never going negative
- A single pass suffices, making it suitable for streaming data
Complexity
- Time: O(n) where n is the number of elements. Each element is visited exactly once with constant work per element.
- Space: O(1). Only three scalar variables are maintained regardless of input size.
Solution
from typing import List
def compute_variance(nums: List[float]) -> float:
count = 0
mean = 0.0
squared_deviations = 0.0
for value in nums:
count += 1
delta = value - mean
mean += delta / count
squared_deviations += delta * (value - mean)
return squared_deviations / count