Compute sample variance for a small measurement set
Also published in our Blogger archive.
When several readings are a sample from a larger process, statistics.variance() computes sample variance: the sum of squared deviations divided by N − 1. That denominator is Bessel’s correction. It differs from population variance because the sample mean was estimated from the same observations.
The example uses four exact Fraction measurements: 2, 4, 6, and 8. Their mean is 5; their squared deviations total 20; dividing by three gives the exact sample variance 20/3. Fraction avoids an unnecessary floating-point display approximation, so the assertion can compare the mathematical result exactly. The program prints the resulting spread measure as a compact report.
Use variance() only when these values are a sample and there are at least two real-valued observations. For the complete population, use pvariance() instead. A larger variance means more spread around the mean, but it does not identify a cause, establish normality, or prove that a tiny sample represents a broader population. The optional xbar argument can avoid recalculating a known sample mean, but Python does not verify that supplied value; a wrong mean can produce an invalid result. The statistics module was added in Python 3.4. Its requirements, Bessel correction, and support for exact numeric types are documented in the official Python documentation.
AI assistance disclosure: this article was drafted with AI assistance and its example was synthetically tested.
from fractions import Fraction
from statistics import variance
measurements = [Fraction(2), Fraction(4), Fraction(6), Fraction(8)]
spread = variance(measurements)
assert spread == Fraction(20, 3)
print(f"sample variance: {spread}")
sample variance: 20/3