Overview
The mean tells you where the data sit. The standard deviation tells you how far a typical value is from there. To get it, measure each value's distance from the mean, square the distances so that negatives and positives do not cancel, average them, and take the square root to return to the original unit. A small result means the values huddle near the mean, and a large one means they are spread out. For data shaped like a normal distribution, about 68 percent of values lie within one standard deviation of the mean and about 95 percent within two. It is the unit in which statistics measures distance.
A short history
Karl Pearson introduced the term standard deviation in the 1890s as a replacement for older names such as root mean square error, which astronomers and Carl Friedrich Gauss had used earlier in the century in the theory of errors. Because it is in the same unit as the data and scales the normal curve, it became the default measure of spread. Friedrich Bessel's correction, dividing by n minus 1, is used when it is estimated from a sample.
How it works
- Compute the mean of the values.
- Subtract the mean from each value and square the result.
- Add the squares and divide by for a sample (ddof 1) or by for a whole population (ddof 0).
- Take the square root.
- For the standard error of the mean, divide the standard deviation by the square root of .
- For z-scores, subtract the mean from each value and divide by the standard deviation.
- For data that arrive one value at a time, feed them to RunningStd, which keeps a running mean and sum of squares and never stores the values.
Watch out for
- Outliers inflate it, because deviations are squared before they are averaged. One extreme value can double the result.
- The 68 and 95 percent figures hold for normal data only. On skewed or heavy-tailed data they can be far off.
- Dividing by on a sample understates the spread, because the mean was fitted to the same values and sits closer to them than the true mean does.
- The standard deviation describes the spread of the data. The standard error describes the uncertainty of the mean. Quoting one where the other is meant overstates or understates precision.
- Z-scores are undefined when every value is the same, since the standard deviation is zero. The template raises an error.
Use cases
When to use it
As the default measure of spread for roughly symmetric numeric data, and as the unit behind z-scores, standardising features, confidence intervals and effect sizes.
In industry
- Manufacturing
- Process control charts, introduced by Walter Shewhart at Bell Labs in the 1920s, place limits at three standard deviations around the process mean.
- Finance
- The volatility of an asset is quoted as the standard deviation of its returns over a period.
- Machine learning
- Features are standardised by subtracting the mean and dividing by the standard deviation before training models that are sensitive to scale.
Choosing it: what must hold
- Interval or ratio data for which the mean is a sensible centre.
- A distribution that is roughly symmetric and free of extreme outliers, since squared deviations give extremes great weight.
- A choice between the population formula and the sample formula with n minus 1 that matches your data.
When to choose something else
| If | Use instead |
|---|---|
| The data are skewed or have outliers | Quartiles and IQR, or the median absolute deviation |
| You are comparing spread across variables with different units or sizes | Coefficient of variation |
| You need to add or split spread across independent sources | Variance, which is additive |
Math foundations
Sample standard deviation
The root of the average squared deviation. Dividing by is Bessel's correction, which makes the variance unbiased for a sample. For a whole population divide by .
Standard error of the mean
How far the sample mean typically lies from the true mean. It shrinks as the sample grows, while itself does not.
Z-score
A value expressed as a number of standard deviations above or below the mean. Z-scores have mean 0 and standard deviation 1, which puts different columns on a common scale.
Pooled standard deviation
One spread estimated from several samples that are assumed to share it. Each sample's variance is weighted by its degrees of freedom.
Welford's one-pass update
The running mean and running sum of squared deviations after the -th value. At any point . It avoids the rounding errors of subtracting two large sums.
Symbols
- the i-th value
- the mean of the values
- number of values
- the standard deviation
- the z-score of the i-th value
- size and standard deviation of the j-th sample
- running mean after k values
- running sum of squared deviations after k values
Worked by hand
Eight values: 2, 4, 4, 4, 5, 5, 7, 9. Their sum is 40, so the mean is 5.
The sample standard deviation is 2.138, a little above the population value of 2. The mean of 5 is known to within about 0.76, and the value 9 sits 1.87 standard deviations above it.
Visual example
Loading the example.
Try this
- Drag the value at 9 out to 12 and watch the band widen while its z-score grows.
- Step k from 1 up to 8 and follow the mean and the running sum S as each value arrives.
- Switch between dividing by n and by n minus 1: s moves between 2 and 2.138 for the starting values.
Code sample
import numpy as np
from impl import StandardDeviation, RunningStd
from config import StandardDeviationConfig
x = [2, 4, 4, 4, 5, 5, 7, 9]
print(StandardDeviation(StandardDeviationConfig(ddof=0)).std(x)) # 2.0
print(StandardDeviation().std(x)) # 2.138 (sample)
print(StandardDeviation().zscores(x))
running = RunningStd()
for value in x:
running.update(value)
print(running.std) # 2.138Read the implementation (115 lines)
"""Standard deviation: the root mean squared deviation from the mean, in the units of the data.
NumPy only. Besides the plain and frequency-weighted standard deviation this gives the standard error of the mean,
z-scores, the pooled standard deviation of several samples, and a one-pass running version (Welford's method) for
streams that do not fit in memory.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import StandardDeviationConfig
except ImportError: # run from the template's own folder
from config import StandardDeviationConfig
class StandardDeviation:
"""Standard deviation and the quantities built directly on it."""
def __init__(self, config: StandardDeviationConfig | None = None) -> None:
self.config = config or StandardDeviationConfig()
def std(self, values, weights=None) -> np.ndarray | float:
"""Standard deviation.
values: array-like of any shape. weights: optional non-negative frequency weights with one entry per
value along config.axis (or per element when axis is None); a weight of 3 counts the value three times.
Returns a float when config.axis is None, otherwise an array with that axis removed.
"""
x = np.asarray(values, dtype=float)
axis = self.config.axis
if axis is None:
x, axis = x.ravel(), 0
x = np.moveaxis(x, axis, 0) # reduce over the first axis
if weights is None:
w = np.ones(x.shape[0])
else:
w = np.asarray(weights, dtype=float).ravel()
if w.size != x.shape[0] or (w < 0).any():
raise ValueError("weights must be non-negative with one entry per value")
total = w.sum()
if total - self.config.ddof <= 0:
raise ValueError("not enough values for the chosen ddof")
w = w.reshape((-1,) + (1,) * (x.ndim - 1))
mean = (w * x).sum(axis=0) / total
variance = (w * (x - mean) ** 2).sum(axis=0) / (total - self.config.ddof)
result = np.sqrt(variance)
return float(result) if result.ndim == 0 else result
def standard_error(self, values) -> np.ndarray | float:
"""Standard error of the mean, std / sqrt(n): how far the sample mean typically is from the true mean."""
x = np.asarray(values, dtype=float)
n = x.size if self.config.axis is None else x.shape[self.config.axis]
return self.std(x) / math.sqrt(n)
def zscores(self, values) -> np.ndarray:
"""(x - mean) / std along config.axis: each value as a number of standard deviations from the mean.
Returns an array of the input's shape. Raises ValueError when the standard deviation is zero.
"""
x = np.asarray(values, dtype=float)
axis = self.config.axis
std = np.asarray(self.std(x))
if (std == 0).any():
raise ValueError("z-scores are undefined when the standard deviation is zero")
if axis is None:
return (x - x.mean()) / std
return (x - x.mean(axis=axis, keepdims=True)) / np.expand_dims(std, axis)
@staticmethod
def pooled(*samples) -> float:
"""Pooled standard deviation sqrt(sum((n_i - 1) * s_i^2) / sum(n_i - 1)) of two or more samples.
Each sample is array-like of shape (n_i,) with n_i >= 2. This is the common spread assumed by the
two-sample t test and by Cohen's d.
"""
if len(samples) < 2:
raise ValueError("pooling needs at least two samples")
numerator, denominator = 0.0, 0
for sample in samples:
x = np.asarray(sample, dtype=float).ravel()
if x.size < 2:
raise ValueError("every sample needs at least two values")
numerator += float(((x - x.mean()) ** 2).sum())
denominator += x.size - 1
return math.sqrt(numerator / denominator)
class RunningStd:
"""One-pass standard deviation (Welford): feed values one at a time, read the result at any point."""
def __init__(self, ddof: int = 1) -> None:
if ddof not in (0, 1):
raise ValueError(f"ddof must be 0 or 1, got {ddof}")
self.ddof = ddof
self.n = 0
self.mean = 0.0
self._sum_squares = 0.0 # sum of squared deviations from the current mean
def update(self, value: float) -> "RunningStd":
"""Add one value. Returns self so calls can be chained."""
self.n += 1
delta = value - self.mean
self.mean += delta / self.n
self._sum_squares += delta * (value - self.mean)
return self
@property
def std(self) -> float:
"""Standard deviation of the values seen so far."""
if self.n - self.ddof <= 0:
raise ValueError("not enough values for the chosen ddof")
return math.sqrt(self._sum_squares / (self.n - self.ddof))- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 9, run with
python3 -m unittest -v
Practice
Compute StandardDeviation().std on the eight values above, then again with StandardDeviationConfig(ddof=0). Feed the same values one at a time to RunningStd with update and read std after each, checking that the last matches. Finally call zscores and confirm that the results have mean 0.
Check on learning
- Why does dividing by understate the spread of the population when you only have a sample?
A way to think about it
The sample mean is the point that minimises the sum of squared deviations for these values. The true mean is some other point, so deviations from it are larger on average.
- You quadruple the sample size. What happens to the standard deviation, and what happens to the standard error of the mean?
A way to think about it
One of them estimates a fixed property of the population. The other has in its denominator.
- A column has a standard deviation of 15 and one value 200 units from the mean. How would you decide whether to report the standard deviation at all?
A way to think about it
Recompute without that value and compare. Then consider a spread measure built from quartiles.
- Why would you standardise features to z-scores before a method that uses distances between rows?
A way to think about it
Take one feature in metres and one in millimetres and ask which dominates a Euclidean distance.
- The formula mean of squares minus square of the mean also gives the variance in one pass. Why does Welford's update exist?
A way to think about it
Try values like 1 000 000 000.1 and 1 000 000 000.2. Both terms are huge and nearly equal, and their difference loses most of its digits.