Sign in

Standard deviation

The standard deviation is the square root of the variance: the typical distance of a value from the mean, in the data's own unit.

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

  1. Compute the mean of the values.
  2. Subtract the mean from each value and square the result.
  3. Add the squares and divide by n−1n - 1 for a sample (ddof 1) or by nn for a whole population (ddof 0).
  4. Take the square root.
  5. For the standard error of the mean, divide the standard deviation by the square root of nn.
  6. For z-scores, subtract the mean from each value and divide by the standard deviation.
  7. 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 nn 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

IfUse instead
The data are skewed or have outliersQuartiles and IQR, or the median absolute deviation
You are comparing spread across variables with different units or sizesCoefficient of variation
You need to add or split spread across independent sourcesVariance, which is additive

Math foundations

  1. Sample standard deviation

    s=1n−1∑i=1n(xi−xˉ)2s = \sqrt{\frac{1}{n-1} \sum_{i=1}^{n} (x_i - \bar{x})^{2}}

    The root of the average squared deviation. Dividing by n−1n - 1 is Bessel's correction, which makes the variance s2s^{2} unbiased for a sample. For a whole population divide by nn.

  2. Standard error of the mean

    SE(xˉ)=sn\mathrm{SE}(\bar{x}) = \frac{s}{\sqrt{n}}

    How far the sample mean typically lies from the true mean. It shrinks as the sample grows, while ss itself does not.

  3. Z-score

    zi=xi−xˉsz_i = \frac{x_i - \bar{x}}{s}

    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.

  4. Pooled standard deviation

    sp=∑j(nj−1) sj2∑j(nj−1)s_p = \sqrt{\frac{\sum_{j} (n_j - 1)\, s_j^{2}}{\sum_{j} (n_j - 1)}}

    One spread estimated from several samples that are assumed to share it. Each sample's variance is weighted by its degrees of freedom.

  5. Welford's one-pass update

    Mk=Mk−1+xk−Mk−1k,Sk=Sk−1+(xk−Mk−1)(xk−Mk)M_k = M_{k-1} + \frac{x_k - M_{k-1}}{k}, \qquad S_k = S_{k-1} + (x_k - M_{k-1})(x_k - M_k)

    The running mean MM and running sum of squared deviations SS after the kk-th value. At any point s=Sk/(k−1)s = \sqrt{S_k / (k - 1)}. It avoids the rounding errors of subtracting two large sums.

Symbols

xix_i
the i-th value
xˉ\bar{x}
the mean of the values
nn
number of values
ss
the standard deviation
ziz_i
the z-score of the i-th value
nj,sjn_j, s_j
size and standard deviation of the j-th sample
MkM_k
running mean after k values
SkS_k
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.

∑(xi−5)2=9+1+1+1+0+0+4+16=32\sum (x_i - 5)^{2} = 9 + 1 + 1 + 1 + 0 + 0 + 4 + 16 = 32
σ=328=2(population)\sigma = \sqrt{\frac{32}{8}} = 2 \quad (\text{population})
s=327=4.571=2.138(sample)s = \sqrt{\frac{32}{7}} = \sqrt{4.571} = 2.138 \quad (\text{sample})
SE(xˉ)=2.1388=0.756\mathrm{SE}(\bar{x}) = \frac{2.138}{\sqrt{8}} = 0.756
z8=9−52.138=1.871z_8 = \frac{9 - 5}{2.138} = 1.871

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.138
Read 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

  1. Why does dividing by nn 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.

  2. 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 n\sqrt{n} in its denominator.

  3. 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.

  4. 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.

  5. 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.