Variation
Sample Variance
Measure how spread out the data is. Compute the mean, then average the
squared deviations from it — dividing by n−1 (Bessel's correction) to
get an unbiased estimate of the population variance. By hand, two loops:
one for the mean, one for the squared deviations. With the library,
statistics.variance uses the same n−1 denominator.
By hand
With the library
statistics.variance uses n−1 and matches the naive result exactly.
np.var defaults to ddof=0 (population variance, divides by n) — pass
ddof=1 to get the sample variance. The snapshot shows all three side by
side to make the ddof difference concrete.
naive.py
values = [4, 8, 6, 13, 10, 6, 9]
n = len(values)
total = 0.0
for v in values:
total = total + v
mean = total / n
sq_diff = 0.0
for v in values:
sq_diff = sq_diff + (v - mean) ** 2
variance = sq_diff / (n - 1)
print('RESULT:', round(variance, 10))
library.py
import statistics
import numpy as np
from dalib.display import set_display
set_display()
values = [4, 8, 6, 13, 10, 6, 9]
var_stdlib = float(statistics.variance(values))
var_np_pop = float(np.var(values))
var_np_samp = float(np.var(values, ddof=1))
print('statistics.variance:', var_stdlib)
print('np.var (ddof=0): ', round(var_np_pop, 4))
print('np.var (ddof=1): ', var_np_samp)
print('RESULT:', round(var_stdlib, 10))
statistics.variance: 9.0
np.var (ddof=0): 7.7143
np.var (ddof=1): 9.0
RESULT: 9.0
Implementation notes
- Dividing by n−1 instead of n is Bessel's correction: the sample mean slightly underestimates deviations from the true population mean, so shrinking the denominator compensates. Dividing by n gives the population variance, which is correct only when you have the full population.
np.vardefault isddof=0(population). Always passddof=1when you want sample variance from numpy.statistics.variancealways uses n−1; there is no ddof parameter.