Distinguish population and sample standard deviation
Population and sample standard deviation answer closely related but different questions. statistics.pstdev() divides squared deviations by N and describes a complete population. statistics.stdev() divides by N − 1 and estimates population spread from a sample. The latter is therefore larger for the same non-constant data set.
The eight values in this example are a complete, fixed numeric set used for comparison. The code calculates both functions, asserts their rounded values, and verifies the expected ordering before printing three decimal places. The output is deterministic while retaining enough precision to show the distinction: population standard deviation is 2.000 and sample standard deviation is 2.138.
The assertions confirm these computations for these inputs only; they cannot determine whether a real-world collection is genuinely a complete population or a representative sample. That classification comes from how the data was collected. Both functions require numeric, non-empty data; stdev() additionally needs at least two values. For a dataset with no variation, both can be zero, so the sample-is-larger comparison is not a general rule without the non-constant condition. The statistics module was added in Python 3.4. See the official documentation for pstdev and stdev for their variance-based definitions.
AI assistance disclosure: this article was drafted with AI assistance and its example was synthetically tested.
from statistics import pstdev, stdev
values = [2, 4, 4, 4, 5, 5, 7, 9]
population = pstdev(values)
sample = stdev(values)
assert round(population, 3) == 2.000
assert round(sample, 3) == 2.138
assert sample > population
print(f"population: {population:.3f}")
print(f"sample: {sample:.3f}")
population: 2.000
sample: 2.138
Comments
Post a Comment