Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Descriptive statistics

ProblemSummarise a sample by its location, spread and shape: means, variance, quantiles, robust measures, skewness and kurtosis
Devised byKarl Pearson (1890s), moments, skewness and the standard deviation; B. P. Welford (1962), one-pass updating; Tony Chan, Gene Golub and Randall LeVeque (1983), analysis of variance algorithms; John Tukey (1977), the five-number summary; Frank Hampel (1974), robustness and the median absolute deviation; Rob Hyndman and Yanan Fan (1996), sample quantile definitions
AccuracyMean and variance to a few units in the last place regardless of the offset of the data (figure below); values agree with SciPy and NumPy to
Cost for moments; for quantiles (a sort)
Read firstPreliminaries: probability
APIdescriptive: mean, variance, standard_deviation, standard_error, weighted_mean, geometric_mean, harmonic_mean, quantile, median, interquartile_range, median_absolute_deviation, skewness, excess_kurtosis, summary

Overview

Descriptive statistics compress a sample into a few numbers. Location says where the data sit (mean, median), spread how far they scatter (standard deviation, interquartile range, median absolute deviation), and shape how they depart from symmetry and from normal tails (skewness, kurtosis). Two questions recur. Is the computation numerically sound, given that data often carry a large common offset? And is the statistic robust, or can a single wild value move it arbitrarily far?

Where it is used

Descriptive statistics summarise a data set before any model is used.

  • Quality control and measurement. Mean and standard deviation of a production batch, and the quantiles used for specification limits.
  • Robust summaries. The median and the median absolute deviation are not thrown off by outliers, a common situation with sensor data.
  • Shape. Skewness and kurtosis flag heavy tails or asymmetry, as in noise statistics and financial returns.

History

Karl Pearson introduced the term “standard deviation” (1893) and the moment measures of skewness and kurtosis in the 1890s, building on Gauss’s and Laplace’s theory of errors. R. A. Fisher’s -statistics (1929) gave unbiased versions. As computers arrived, the textbook “one-pass” variance formula was found to fail on real data; B. P. Welford (1962) proposed a stable updating formula, and Tony Chan, Gene Golub and Randall LeVeque (1983) analysed all the variants, recommending the corrected two-pass algorithm when the data can be read twice. John Tukey’s Exploratory Data Analysis (1977) popularised medians, quartiles and the box plot; Frank Hampel (1968, 1974) founded robust statistics with the influence function and the breakdown point. Rob Hyndman and Yanan Fan (1996) catalogued nine competing definitions of the sample quantile used by statistical packages.

The idea

The mean and compensated summation

The mean is the value that minimises the sum of squared deviations , which is why it is called the least-squares estimate of location.

Computing it requires a sum, and even a sum deserves care. Each floating-point addition rounds its result, and when a small number is added to a large running total the low digits of the small number are lost. Over additions these errors accumulate and grow with . The library uses Neumaier’s compensated summation: after each addition it works out, exactly, the rounding error that the addition just made (this is possible with two further floating-point operations) and accumulates those errors in a second variable, which is added to the total at the end. The sum is then accurate to a few units in the last place for any . Weighted, geometric ( of the mean log) and harmonic (reciprocal of the mean reciprocal) means are also provided.

The variance: why the textbook formula fails

The sample variance is the average squared deviation from the mean,

The divisor is and not (ddof = 1) because the deviations are measured from the sample mean, which was itself fitted to the data and so lies closer to the data than the true mean does; dividing by compensates exactly, making an unbiased estimate of the true variance.

Expanding the square gives the algebraically equivalent formula , which appears in many textbooks because it needs only a single pass over the data. Numerically it is a trap. Suppose the data are near and vary by about 1. Then and are both about and agree in their first sixteen digits, while their difference, the quantity wanted, is only about . Double precision holds sixteen digits, so the subtraction cancels every one of them and leaves rounding error. This is catastrophic cancellation.

The library uses the corrected two-pass algorithm instead. The first pass computes . The second computes the deviations , which are small numbers computed accurately, and forms

In exact arithmetic the deviations sum to zero and the second term vanishes. In floating point the computed mean is slightly off, the deviations sum to a small nonzero number, and the second term removes the resulting error.

Figure 10.1. Variance accuracy.

For 1000 values with uniform on , the one-pass formula loses all accuracy once (its errors above are clipped), Welford’s one-pass update degrades more slowly, and the two-pass algorithm stays at rounding level for every offset.

Quantiles

The -quantile splits the data so that a fraction lies below it. For a finite sample this does not define a unique number: with four values, any number between the second and the third has half the data below it. Hyndman and Fan catalogued nine definitions in use. The library uses their type 7, the default of R and NumPy. Sort the data into the order statistics , place them at equally spaced positions from 0 to , and read off the value at position , interpolating linearly between the two neighbouring order statistics and when is not a whole number. For the data and , , halfway between the second and third values: the median is 3. The median is the 0.5-quantile, the quartiles the 0.25 and 0.75 quantiles, and summary returns Tukey’s five-number summary with the count, mean and standard deviation.

Robustness and the breakdown point

The breakdown point of an estimator is the largest fraction of the data that can be replaced by arbitrary values without carrying the estimate arbitrarily far. The mean and standard deviation have breakdown point 0: a single value suffices. The median and the median absolute deviation have breakdown point 50%, the largest possible; the interquartile range has 25%. Scaled by , the MAD estimates for normal data, as does .

As standard normal data are progressively replaced by values near 10, the mean and standard deviation drift at once; the interquartile range holds until a quarter of the data are contaminated and then jumps; the median and MAD drift only slowly until half are.

Shape: skewness and kurtosis

With central moments , the skewness measures asymmetry (positive for a long right tail) and the excess kurtosis measures tail weight relative to the normal distribution, for which it is 0. These are the biased versions, as in scipy.stats.skew and kurtosis; both are very sensitive to outliers, since they raise deviations to the third and fourth powers.

Algorithm

Sum and mean (Neumaier’s compensated summation). Keep a running sum and a compensation , both initially zero. For each value :

  1. compute ;
  2. if , add to ; otherwise add to . In either case this is the part of the smaller number that was lost when it was added to the larger;
  3. set .

The sum is , and the mean is the sum divided by .

Variance with ddof degrees of freedom removed (1 for the sample variance, 0 for the population variance):

  1. compute the mean ;
  2. in a second pass, accumulate and ;
  3. return .

Quantile at level :

  1. reject data containing NaN, and sort a copy;
  2. compute the position and its integer part ;
  3. return , or simply when .

Median absolute deviation: compute the median ; form the absolute deviations ; return their median.

The mean and variance cost ; the order-based statistics cost a sort, .

Implementation

/// The arithmetic mean.
pub fn mean(x: &[f64]) -> Result<f64, ErrorsJSL> {
    non_empty(x)?;
    // Pairwise-free compensated (Neumaier) summation keeps the mean accurate for long samples.
    let (mut sum, mut compensation) = (0.0f64, 0.0f64);
    for &v in x {
        let t = sum + v;
        compensation += if sum.abs() >= v.abs() { (sum - t) + v } else { (v - t) + sum };
        sum = t;
    }
    Ok((sum + compensation) / x.len() as f64)
}

/// The variance with `ddof` delta degrees of freedom: `Σ(x − x̄)² / (n − ddof)` (1 for the
/// unbiased sample variance, 0 for the population variance). Two-pass for accuracy.
pub fn variance(x: &[f64], ddof: usize) -> Result<f64, ErrorsJSL> {
    if x.len() <= ddof {
        return Err(ErrorsJSL::InvalidInputRange("Need more samples than delta degrees of freedom."));
    }
    let m = mean(x)?;
    let (sum_sq, sum) = x.iter().fold((0.0, 0.0), |(s2, s1), &v| (s2 + (v - m) * (v - m), s1 + (v - m)));
    // The second term corrects the rounding left in the mean.
    Ok((sum_sq - sum * sum / x.len() as f64) / (x.len() - ddof) as f64)
}
fn quantile_sorted(s: &[f64], p: f64) -> f64 {
    let h = (s.len() - 1) as f64 * p;
    let (lo, frac) = (h.floor() as usize, h - h.floor());
    if lo + 1 < s.len() { s[lo] + frac * (s[lo + 1] - s[lo]) } else { s[lo] }
}

Against SciPy 1.17 and NumPy 2.4 on a skewed sample of 20 values (the kernel density estimate is included for completeness):

Table 10.1. Descriptive statistics against SciPy and NumPy.

quantitylibrarySciPy / NumPyrelative difference
variance (ddof 1)1.7927601.7927600
skewness1.8491881.8491881.2e-16
excess kurtosis2.7468762.7468766.5e-16
quantile 0.1 (type 7)0.1422000.1422000
median absolute deviation (normal scale)0.6137970.6137970
Gaussian KDE (Scott) at 0.00.2849930.2849930
Gaussian KDE (Scott) at 0.50.3799520.3799525.8e-16
Gaussian KDE (Scott) at 1.50.2519930.2519930
Gaussian KDE (Scott) at 3.00.0644040.0644040
  • Every function returns an error for an empty sample; quantile functions reject NaN; geometric and harmonic means need positive values.

In practice

//! Summarise a skewed sample, robustly and otherwise.

use lib_jsl_statistics::descriptive::*;

fn main() {
    // Household incomes in thousands, with one very large value.
    let income = [28.0, 35.5, 41.0, 39.2, 52.8, 47.1, 33.4, 61.0, 44.6, 38.9, 55.3, 1250.0];
    let s = summary(&income).unwrap();
    println!("n = {}, mean = {:.1}, sd = {:.1}", s.count, s.mean, s.standard_deviation);
    println!("five-number summary: {:.1} {:.1} {:.1} {:.1} {:.1}", s.minimum, s.first_quartile, s.median, s.third_quartile, s.maximum);
    println!("robust spread: IQR = {:.1}, 1.4826 MAD = {:.1}", interquartile_range(&income).unwrap(), median_absolute_deviation(&income, 1.4826).unwrap());
    println!("skewness = {:.2}, excess kurtosis = {:.2}", skewness(&income).unwrap(), excess_kurtosis(&income).unwrap());
    println!("geometric mean = {:.1}, 90th percentile = {:.1}", geometric_mean(&income).unwrap(), quantile(&income, 0.9).unwrap());
}
n = 12, mean = 143.9, sd = 348.5
five-number summary: 28.0 38.0 42.8 53.4 1250.0
robust spread: IQR = 15.4, 1.4826 MAD = 12.4
skewness = 3.01, excess kurtosis = 7.08
geometric mean = 56.1, 90th percentile = 60.4

One income of 1250 makes the mean more than three times the median and the standard deviation 28 times the MAD.

Strengths

  • Numerically robust mean and variance; quantiles compatible with R and NumPy.
  • Robust alternatives (median, IQR, MAD) alongside the classical statistics.

Weaknesses

  • Quantiles sort a copy of the data, ; selection algorithms would be .
  • No one-pass (streaming) accumulator; Welford’s update would be needed for data seen once.

Exercises

  1. Show that when dividing by , and find the bias when dividing by .
  2. Derive Welford’s update , .
  3. Show that the correction term in the two-pass algorithm is zero in exact arithmetic, and estimate its size in floating point.
  4. Compute the breakdown points of the trimmed mean that discards the top and bottom 10%, and of the interquartile range.
  5. Compute the type 7 and type 6 () quantiles of at .
Hints and answers
  1. , so dividing by is unbiased and dividing by has bias .
  2. from . Then follows by expanding in terms of .
  3. is zero by the definition of the mean; in floating point it is of the order of , which is why it corrects the rounding in .
  4. The 10% trimmed mean breaks down when 10% of the data are corrupted (the trimmed tail can absorb only that fraction); the interquartile range breaks down at 25%.
  5. Type 7: position (0-based), so . Type 6: position is below the first element, so the result is clamped to the minimum, .

Further reading

  • T. F. Chan, G. H. Golub and R. J. LeVeque, “Algorithms for computing the sample variance: analysis and recommendations”, The American Statistician 37 (1983) 242–247.
  • B. P. Welford, “Note on a method for calculating corrected sums of squares and products”, Technometrics 4 (1962) 419–420.
  • R. J. Hyndman and Y. Fan, “Sample quantiles in statistical packages”, The American Statistician 50 (1996) 361–365.
  • P. J. Huber and E. M. Ronchetti, Robust Statistics, 2nd ed., Wiley, 2009.
  • J. W. Tukey, Exploratory Data Analysis, Addison-Wesley, 1977.