Hypothesis tests
| Problem | Decide whether data are consistent with a null hypothesis (equal means, a given distribution, independence) and quantify the evidence against it by a p-value |
| Devised by | Karl Pearson (1900), the test; “Student” (William Sealy Gosset, 1908), the test; R. A. Fisher (1920s), significance testing and the analysis of variance; Jerzy Neyman and Egon Pearson (1933), errors of two kinds and power; Andrey Kolmogorov (1933) and Nikolai Smirnov (1939), distribution tests; Frank Wilcoxon (1945), Henry Mann and Donald Whitney (1947), rank tests; Bernard Welch (1947), unequal variances |
| Accuracy | Statistics and p-values agree with SciPy to for every test with an exact reference distribution; the Kolmogorov-Smirnov p-values are asymptotic approximations (table below) |
| Cost | for the tests, and ANOVA; for the rank and Kolmogorov-Smirnov tests |
| Read first | Descriptive statistics, Statistical distribution functions |
| API | hypothesis_tests: t_test_one_sample, t_test_two_sample, t_test_paired, chi_square_goodness_of_fit, chi_square_independence, anova_one_way, ks_test_one_sample, ks_test_two_sample, mann_whitney_u, kolmogorov_survival, Alternative, TestResult |
Overview
A hypothesis test computes a statistic that measures departure from a null hypothesis , and its p-value: the probability,
if were true, of a statistic at least as extreme as the one observed. A small p-value is evidence against ; rejecting when
makes the probability of a false rejection (the size, or type I error rate) equal to , provided the reference distribution
is right. The probability of rejecting when is false is the power. Every test here returns a TestResult with the statistic, the
p-value and the degrees of freedom, and the location tests accept a two-sided or one-sided Alternative.
Tests fall into two families. Parametric tests (, ANOVA) assume normal data and are the most powerful when that holds. Nonparametric tests (rank tests, Kolmogorov-Smirnov) assume only continuity, and keep their size and power when tails are heavy.
Where it is used
Hypothesis tests decide whether an observed difference could be chance.
- Engineering and manufacturing. Is a new process better than the old? Do two suppliers’ parts have the same mean strength?
- Medicine and biology. Clinical trials and lab experiments compare treated and control groups.
- A/B testing. Comparing two versions of a web page or an algorithm.
- Goodness of fit. Whether data follow a claimed distribution, such as noise that is meant to be Gaussian.
History
Karl Pearson’s test of goodness of fit (1900) was the first modern significance test. William Sealy Gosset, a chemist at the Guinness brewery in Dublin, published the distribution under the pseudonym “Student” (1908) to handle the small samples of brewing experiments; R. A. Fisher proved it, extended it to two samples and regression, and invented the analysis of variance (1918–1925) for agricultural field trials at Rothamsted. Jerzy Neyman and Egon Pearson (1933) recast testing as a decision between hypotheses with errors of two kinds. Andrey Kolmogorov (1933) found the limiting distribution of the largest deviation of an empirical distribution function, and Nikolai Smirnov (1939) extended it to two samples. Frank Wilcoxon (1945) proposed rank-sum tests, and Henry Mann and Donald Whitney (1947) studied them. Bernard Welch (1947) and Franklin Satterthwaite (1946) solved the practical side of the Behrens-Fisher problem of comparing means with unequal variances.
The idea
Student’s and Welch’s tests
Every test in this entry follows the same three steps. First, reduce the data to a single number, the statistic, that is near zero (or near some known value) when the null hypothesis is true and far from it otherwise. Second, work out the reference distribution: how the statistic would vary from sample to sample if were true. Third, report the p-value, the probability under that distribution of a value at least as extreme as the one observed. The tests differ only in the statistic and its reference distribution.
One sample. The question is whether a sample of size , with mean and standard deviation , is consistent with a population mean . The natural measure is the distance of the sample mean from . But a distance of 1 means little without knowing how much fluctuates by chance: its standard deviation is , estimated by (the standard error). The statistic is the distance in units of the standard error:
If were known exactly, this would have a standard normal distribution for normal data. Because is only an estimate, varies a little more, especially for small . Its exact distribution, worked out by Gosset (“Student”), is Student’s distribution with degrees of freedom. It has heavier tails than the normal and approaches it as grows.
Paired samples. When each observation in one sample is matched with one in the other (before and after a treatment, say), take the differences and apply the one-sample test to them with .
Two independent samples. To compare the means of two groups, the statistic is the difference of the means divided by its standard error. There are two ways to estimate that standard error.
- Student’s test assumes that the two populations have the same variance and pools the two estimates of it: . The reference distribution is with degrees of freedom.
- Welch’s test makes no such assumption. The variance of a difference of independent means is the sum of their variances, so
This statistic does not have an exact distribution, but it is well approximated by one with a non-integer number of degrees of freedom given by the Welch-Satterthwaite formula
Welch’s test is the safer default: when the smaller sample has the larger variance, Student’s test rejects a true null five times as often as it should (table below), while Welch’s loses almost nothing when the variances are equal.
Chi-square tests for counts
When the data are counts of observations falling into categories, the null hypothesis specifies the expected count in each of the categories, and the test asks whether the observed counts differ from them by more than chance. Pearson’s statistic adds up the squared discrepancies, each scaled by its expected count:
The scaling is what makes the terms comparable: a count with expectation fluctuates by about , so each term is roughly the square of a standardised deviation. For large counts those deviations are approximately normal, and a sum of squared normals has a chi-square distribution. The counts must add up to the total, which removes one degree of freedom.
- Goodness of fit. For a fully specified set of expected counts, is approximately with degrees of freedom.
- Independence. For a table with rows and columns, the null hypothesis is that the row and column classifications are independent. Then the probability of a cell is the product of its row and column probabilities, and the expected counts are , from the row totals , the column totals and the grand total . The statistic has degrees of freedom.
Both rest on the normal approximation to counts, which needs expected counts of about 5 or more.
One-way analysis of variance
To compare the means of groups at once, analysis of variance (ANOVA) asks whether the group means differ from each other by more than the scatter inside the groups can explain. It splits the total sum of squared deviations from the overall mean into two parts:
- , the spread between groups: how far the group means lie from the overall mean;
- , the spread within groups: how far the observations lie from their own group mean.
Dividing each by its degrees of freedom gives two estimates of the variance. The within-group one, , always estimates the noise variance. The between-group one, , estimates the same quantity if the true means are equal, and something larger if they are not. Their ratio
is therefore near 1 under and large otherwise. For normal groups with equal variances and equal means it has the distribution with degrees of freedom. With two groups, ANOVA is equivalent to Student’s test, with .
The library computes the upper tail directly as an incomplete beta function; it used to form , which lost every digit of p-values below .
Kolmogorov-Smirnov tests
The tests so far compare means or counts. The Kolmogorov-Smirnov tests compare whole distributions. The empirical distribution function of a sample is the fraction of the observations that are at most : a staircase that rises by at each observation.
One sample. To test whether the sample comes from a specified continuous distribution , the statistic is the largest vertical gap between the staircase and the curve,
A remarkable property makes this practical: under the distribution of is the same whatever is, so one table serves every hypothesis. As grows, converges to the Kolmogorov distribution, whose upper tail is . For finite samples the library uses Stephens’ correction , which is within a fraction of a per cent of the exact p-value (table below).
Two samples. The same statistic applied to two empirical distribution functions tests whether two samples come from the same distribution, with the effective size in place of . The same correction is less accurate there, and for samples of 15 and 25 the p-value is 7% below the exact one.
These tests detect any difference in distribution, in shape or spread as well as in location. The price of that generality is lower power against a pure shift than a test designed for shifts.
The Mann-Whitney test
The Mann-Whitney test is the rank-based counterpart of the two-sample test. It asks whether values from one sample tend to be larger than values from the other, using only their order.
Consider every pair consisting of one value from each sample, pairs in all, and let be the number of pairs in which the first sample’s value is the larger. If the two samples come from the same distribution, each pair is equally likely to go either way, and should be near . In practice is computed without examining every pair: rank the combined samples, add up the ranks of the first sample to get , and then .
Under (identical continuous distributions) has mean and variance
, where and the
sum is a correction for groups of tied values. For samples that are not very small is
approximately normal, and the library uses that approximation with a continuity correction, as
SciPy’s method="asymptotic" does.
Because it uses ranks, the test is unaffected by outliers and by the shape of the distribution. It gives up very little when the data really are normal: against normal shifts its asymptotic efficiency relative to the test is , meaning that it needs only about 5% more data for the same power. For heavy-tailed data it can be far more powerful.
Checking against SciPy
The cases below were computed with scipy.stats (version 1.17.1) by book/generator/data/make_stats_refs.py, and recomputed
with the library. The statistics agree to at least nine digits (the generator asserts it), and every p-value with an exact
reference distribution agrees to rounding:
Table 10.5. Hypothesis tests against SciPy.
| case | statistic (SciPy) | p-value | SciPy p-value | relative difference of p |
|---|---|---|---|---|
| one-sample t, two | 2.0716 | 0.05726 | 0.05726 | 2.3e-15 |
| one-sample t, less | 2.0716 | 0.97137 | 0.97137 | 1.1e-16 |
| one-sample t, greater | 2.0716 | 0.02863 | 0.02863 | 2.3e-15 |
| Student two-sample t | 1.4973 | 0.14258 | 0.14258 | 3.7e-15 |
| Welch t | 1.7173 | 0.09410 | 0.09410 | 8.8e-16 |
| paired t | 2.5052 | 0.02923 | 0.02923 | 2.5e-15 |
| chi-square goodness of fit, uniform | 14.5000 | 0.01273 | 0.01273 | 1.4e-15 |
| chi-square goodness of fit, given | 4.5694 | 0.47065 | 0.47065 | 1.7e-15 |
| chi-square independence, 2 x 3 | 10.4602 | 0.00535 | 0.00535 | 0 |
| one-way ANOVA, 3 groups | 3.4845 | 0.04846 | 0.04846 | 2.1e-15 |
| Kolmogorov-Smirnov vs N(0, 1), asymptotic | 0.2215 | 0.03321 | 0.03945 | 1.6e-1 |
| Kolmogorov-Smirnov vs N(0, 1), exact | 0.2215 | 0.03321 | 0.03325 | 1.3e-3 |
| Kolmogorov-Smirnov two-sample, asymptotic | 0.4400 | 0.03630 | 0.04199 | 1.4e-1 |
| Kolmogorov-Smirnov two-sample, exact | 0.4400 | 0.03630 | 0.03917 | 7.3e-2 |
| Mann-Whitney U, two-sided | 256.0000 | 0.05747 | 0.05747 | 5.4e-15 |
| Mann-Whitney U, less | 256.0000 | 0.97305 | 0.97305 | 1.1e-16 |
| Mann-Whitney U, greater | 256.0000 | 0.02873 | 0.02873 | 5.4e-15 |
| Mann-Whitney U with ties | 105.0000 | 0.91456 | 0.91456 | 0 |
| Pearson r | 0.6061 | 0.00132 | 0.00132 | 1.6e-16 |
| Spearman rho | 0.6423 | 0.00054 | 0.00054 | 8.1e-16 |
| Spearman rho with ties | 0.7501 | 0.00000 | 0.00000 | 1.0e-14 |
| Kendall tau_b | 0.4467 | 0.00175 | 0.00175 | 1.7e-15 |
| Kendall tau_b with ties | 0.6257 | 0.00002 | 0.00002 | 3.5e-15 |
Size: do the tests reject a true null 5% of the time?
Table 10.6. Rejection rates of the tests when the null hypothesis is true.
| test | data (null hypothesis true) | rejection rate at 5% |
|---|---|---|
| one-sample | normal, | 0.0507 |
| one-sample | exponential, | 0.1018 |
| one-sample | exponential, | 0.0567 |
| Student’s two-sample | normal, , equal variances | 0.0513 |
| Student’s two-sample | normal, , | 0.2554 |
| Welch’s | normal, , | 0.0517 |
| paired | normal pairs, correlation 0.8, | 0.0514 |
| Mann-Whitney | normal, | 0.0440 |
| Mann-Whitney | Cauchy, | 0.0476 |
| Kolmogorov-Smirnov, one sample | uniform, | 0.0476 |
| Kolmogorov-Smirnov, two samples | normal, | 0.0386 |
| goodness of fit | 60 rolls of a fair die | 0.0469 |
| independence | table, 200 independent cases | 0.0515 |
| one-way ANOVA | three normal groups of 8 | 0.0508 |
| Pearson | independent normals, | 0.0509 |
| Spearman | independent normals, | 0.0508 |
| Kendall | independent normals, | 0.0471 |
Each rate is over 20000 simulated data sets; its Monte Carlo standard error is about 0.0015.
The tests hold their size when their assumptions hold. Three departures stand out. The test on skewed (exponential) data of size 10 rejects twice as often as it should; the central limit theorem repairs this by . Student’s pooled test with unequal variances and unequal sizes rejects a quarter of true nulls. And the discrete tests are somewhat conservative at small sizes.
Power
For normal data Welch’s test is the most powerful, with Mann-Whitney a close second. For Cauchy data, whose variance is infinite, the test barely gains power with the shift, while the rank and Kolmogorov-Smirnov tests detect it easily.
Algorithm
Every test has the same three steps, and they differ only in the first two.
- Compute the statistic from the data.
- Identify the reference distribution and its parameters (degrees of freedom).
- Evaluate the tail probability with the distribution functions. For a two-sided test on a symmetric distribution, the p-value is twice the lower tail at ; the tail is always computed directly, never as one minus a CDF.
The first two steps for each test:
| Test | Statistic from | Reference distribution |
|---|---|---|
| One-sample and paired | mean and standard deviation (of the differences, if paired) | with degrees of freedom |
| Student’s two-sample | two means and the pooled variance | with |
| Welch’s | two means and two variances | with the Welch-Satterthwaite |
| Chi-square goodness of fit | observed and expected counts | with |
| Chi-square independence | table, with expected counts from its margins | with |
| One-way ANOVA | group means and sums of squares | with |
| Kolmogorov-Smirnov | sorted sample; largest gap to , checked just before and just after each data point | Kolmogorov, with Stephens’ correction |
| Mann-Whitney | ranks of the pooled samples, with average ranks for ties | normal, with tie and continuity corrections |
For the Kolmogorov-Smirnov statistic the empirical distribution function is a staircase, so its largest distance from a continuous occurs at a data point, on one side or the other of the jump: with the data sorted, .
Implementation
/// Two-sample t-test of equal means: Student's pooled-variance test with `equal_variance`,
/// otherwise Welch's test with the Welch-Satterthwaite degrees of freedom.
pub fn t_test_two_sample(x: &[f64], y: &[f64], equal_variance: bool, alternative: Alternative) -> Result<TestResult, ErrorsJSL> {
let (nx, ny) = (x.len() as f64, y.len() as f64);
let (vx, vy) = (variance(x, 1)?, variance(y, 1)?);
let difference = mean(x)? - mean(y)?;
let (t, df) = if equal_variance {
let pooled = ((nx - 1.0) * vx + (ny - 1.0) * vy) / (nx + ny - 2.0);
(difference / (pooled * (1.0 / nx + 1.0 / ny)).sqrt(), nx + ny - 2.0)
} else {
let (a, b) = (vx / nx, vy / ny);
(difference / (a + b).sqrt(), (a + b).powi(2) / (a * a / (nx - 1.0) + b * b / (ny - 1.0)))
};
Ok(TestResult { statistic: t, p_value: tail(|v| student_t_cdf(v, df), t, alternative), degrees_of_freedom: df })
}
/// The Mann-Whitney U test (Wilcoxon rank-sum) for a location shift between two samples. The
/// statistic is `U` of the first sample; the p-value uses the normal approximation with tie and
/// continuity corrections (adequate for samples above about 10 each).
pub fn mann_whitney_u(x: &[f64], y: &[f64], alternative: Alternative) -> Result<TestResult, ErrorsJSL> {
if x.is_empty() || y.is_empty() {
return Err(ErrorsJSL::InvalidInputRange("Both samples must be non-empty."));
}
let (n1, n2) = (x.len() as f64, y.len() as f64);
let combined: Vec<f64> = x.iter().chain(y).copied().collect();
let ranks = rank(&combined);
let r1: f64 = ranks[..x.len()].iter().sum();
let u = r1 - n1 * (n1 + 1.0) / 2.0;
let n = n1 + n2;
// Tie correction Σ(t³ − t).
let mut sorted = combined.clone();
sorted.sort_by(f64::total_cmp);
let mut ties = 0.0;
let mut i = 0;
while i < sorted.len() {
let mut j = i;
while j + 1 < sorted.len() && sorted[j + 1] == sorted[i] {
j += 1;
}
let t = (j - i + 1) as f64;
ties += t * t * t - t;
i = j + 1;
}
let mu = n1 * n2 / 2.0;
let sigma = (n1 * n2 / 12.0 * ((n + 1.0) - ties / (n * (n - 1.0)))).sqrt();
let z = |shift: f64| (u - mu + shift) / sigma;
let p = match alternative {
Alternative::TwoSided => (2.0 * normal_cdf(-((u - mu).abs() - 0.5).max(0.0) / sigma, 0.0, 1.0)).min(1.0),
Alternative::Less => normal_cdf(z(0.5), 0.0, 1.0),
Alternative::Greater => normal_cdf(-z(-0.5), 0.0, 1.0),
};
Ok(TestResult { statistic: u, p_value: p, degrees_of_freedom: f64::NAN })
}
anova_one_wayreturns theTestResult(with the between-groups degrees of freedom) and the within-groups degrees of freedom.chi_square_independenceapplies no continuity correction, asscipy.stats.chi2_contingency(correction=False).
In practice
//! Compare two treatments with parametric and rank tests.
use lib_jsl_statistics::hypothesis_tests::*;
fn main() {
// Recovery times in days under two treatments.
let a = [12.1, 9.8, 11.4, 14.0, 10.2, 13.5, 9.9, 12.8, 11.0, 15.2, 10.7, 12.3];
let b = [8.9, 10.1, 7.5, 9.4, 11.8, 8.2, 9.0, 7.9, 10.5, 30.0];
let welch = t_test_two_sample(&a, &b, false, Alternative::TwoSided).unwrap();
let student = t_test_two_sample(&a, &b, true, Alternative::TwoSided).unwrap();
let u = mann_whitney_u(&a, &b, Alternative::TwoSided).unwrap();
let ks = ks_test_two_sample(&a, &b).unwrap();
println!("Welch t = {:.3} on {:.1} df, p = {:.4}", welch.statistic, welch.degrees_of_freedom, welch.p_value);
println!("Student t = {:.3} on {} df, p = {:.4}", student.statistic, student.degrees_of_freedom, student.p_value);
println!("Mann-Whitney U = {}, p = {:.4}", u.statistic, u.p_value);
println!("Kolmogorov-Smirnov D = {:.3}, p = {:.4}", ks.statistic, ks.p_value);
// A contingency table: side effect (rows) by treatment (columns).
let table = vec![vec![14.0, 5.0], vec![36.0, 45.0]];
let chi = chi_square_independence(&table).unwrap();
println!("chi-square = {:.3} on {} df, p = {:.4}", chi.statistic, chi.degrees_of_freedom, chi.p_value);
}
Welch t = 0.266 on 10.0 df, p = 0.7954
Student t = 0.290 on 20 df, p = 0.7751
Mann-Whitney U = 97, p = 0.0161
Kolmogorov-Smirnov D = 0.600, p = 0.0220
chi-square = 5.263 on 1 df, p = 0.0218
One patient in the second group took 30 days to recover; that value inflates the variance and the tests see nothing, while the rank tests find the shorter recovery times of the other nine.
Strengths
- The classical tests, with p-values matching SciPy; one-sided alternatives for the location tests.
- Rank and distribution tests for data that are not normal.
Weaknesses
- p-values of the rank and Kolmogorov-Smirnov tests are asymptotic; exact small-sample distributions are not implemented.
- No multiple-comparison corrections, post-hoc tests, or tests of normality beyond Kolmogorov-Smirnov.
- A p-value is not the probability that is true, and a non-significant result is not evidence of no effect; report effect sizes and confidence intervals as well.
Exercises
- Show that the paired test is more powerful than the two-sample test when the pairs are positively correlated.
- Verify the Welch-Satterthwaite formula by matching the first two moments of to a scaled .
- Prove that the null distribution of the Kolmogorov-Smirnov statistic does not depend on the continuous .
- Simulate the size of the goodness-of-fit test with 10 categories and expected counts of 1, 2 and 5.
- Run 20 independent tests on null data and estimate the probability that at least one has . How does the Bonferroni correction help?
Hints and answers
- The difference of pairs has variance against for independent samples, so the standard error is smaller by when and the test is more powerful (although it has fewer degrees of freedom).
- Match and of with , to those of ; solving gives .
- is uniform for continuous , and equals for the empirical distribution of the , which does not involve .
- With expected counts of 1 or 2 the chi-square approximation to the statistic is poor, so the actual size differs from the nominal 5% (it is typically conservative or irregular); simulate with many replicates for each case.
- The probability is . With Bonferroni each test uses , making the probability at least one false positive about .
Further reading
- E. L. Lehmann and J. P. Romano, Testing Statistical Hypotheses, 4th ed., Springer, 2022.
- M. A. Stephens, “EDF statistics for goodness of fit and some comparisons”, Journal of the American Statistical Association 69 (1974) 730–737.
- B. L. Welch, “The generalization of ‘Student’s’ problem when several different population variances are involved”, Biometrika 34 (1947) 28–35.
- R. L. Wasserstein and N. A. Lazar, “The ASA statement on p-values: context, process, and purpose”, The American Statistician 70 (2016) 129–133.