Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.
Sample Variance and Bessel's Correction
You have a sample, not the whole population, and you want to estimate the population variance. The obvious formula is biased:
Why n−1? Because you used the same data twice: once to estimate , and again to measure spread around it. The sample mean sits, by construction, in the position that makes the squared deviations as small as possible — so measuring spread around it systematically understates the true spread. Dividing by n−1 corrects for exactly that.
The intuition that sticks: with n=1, the sample mean is the single point, deviation is 0, and dividing by n−1=0 correctly says you have no information about spread. Dividing by n would have claimed a variance of 0, which is a confident lie.
x = [2, 4, 6] mean = 4 squared deviations: 4, 0, 4 sum = 8 biased: 8/3 = 2.667 unbiased: 8/2 = 4.0
This is the entire content of the ddof argument. numpy defaults to ddof=0 (biased) and pandas defaults to ddof=1 (unbiased), which is why df.std() and np.std(df.values) disagree and why that disagreement has cost people hours.
Your task:
Implement sample_variance(x, ddof) from the definition, dividing by n−ddof. Do not call np.var.
Example Tests
Three points, dividing by n
Input: {"x":[2,4,6],"ddof":0}
Expected: 2.66667
The same three points, corrected for the estimated mean
Input: {"x":[2,4,6],"ddof":1}
Expected: 4
Identical observations have no spread either way
Input: {"x":[5,5,5,5],"ddof":1}
Expected: 0
import numpy as np
def sample_variance(x, ddof):
"""
Variance of a sample, with an adjustable denominator.
Args:
x: array of observations, shape (n,)
ddof: delta degrees of freedom. 0 divides by n, 1 divides by n-1.
Returns:
float
"""
# YOUR CODE HERE
pass