Overview
A p-value answers one narrow question. Assume the null hypothesis holds: how often would chance alone produce a result at least this far from what the null predicts? A small p-value means the data would be rare under the null, which counts as evidence against it. A large one means the data are unremarkable. To compute it you need the statistic's distribution under the null, either from theory (normal, , chi-square, ) or by building it yourself. The permutation test does the second: if the group labels do not matter, shuffling them should give differences like the one observed, so the p-value is the share of shuffles that are at least as extreme.
A short history
Karl Pearson computed a tail probability for his chi-square statistic in 1900, and the idea goes back at least to Laplace. Ronald Fisher made the p-value central in 1925 and suggested 0.05 as a convenient threshold. Its misreading as the probability that the null is true became so common that the American Statistical Association issued a statement in 2016 on what p-values do and do not mean.
How it works
- Compute a test statistic from the data and identify its distribution under the null hypothesis.
- Find the two tail probabilities: the chance of a value at or below the observed one, and at or above it.
- Pick the tail the alternative points to: the upper tail for
greater, the lower forless, and twice the smaller tail fortwo-sided. - For chi-square and statistics, which grow with any departure from the null, use the upper tail.
- For a permutation test, pool the two samples, relabel them in every possible way (or many random ways), and recompute the difference of means each time.
- Report the share of relabellings at least as extreme as the observed difference as the p-value.
Watch out for
- A p-value is not the probability that the null hypothesis is true. It is computed assuming the null, so it cannot also measure the null's probability.
- It says nothing about the size of the effect: a tiny effect with a huge sample and a large effect with a small sample can share the same p-value.
- Running many tests and reporting only the smallest p-value makes that number meaningless, because small values are expected by chance among many tries.
- An exact permutation p-value cannot be smaller than one over the number of relabellings, so very small samples can never reach a strict threshold.
- The permutation test here assumes the two samples are exchangeable under the null. It tests equal distributions, so a difference in spread alone can affect it.
Use cases
When to use it
Turning any test statistic into a common evidence scale between 0 and 1, and, through the permutation test, getting a valid p-value when you do not trust a textbook distribution.
In industry
- Medical journals
- Trial reports give a p-value for the primary outcome alongside the effect estimate and confidence interval.
- Genomics
- Genome wide association studies compute a p-value for each of about a million variants and use the threshold of 5 times 10 to the minus 8 to allow for the number of tests.
- Online experimentation
- Experiment platforms show a p-value for each metric so that teams can judge whether a difference could be chance.
Choosing it: what must hold
- A fully specified null hypothesis and a test statistic whose distribution under that null is known.
- An analysis plan fixed before seeing the data; trying many analyses and reporting the smallest p-value invalidates it.
- Correct reading: it is the probability of data this extreme if the null is true, not the probability that the null is true.
When to choose something else
| If | Use instead |
|---|---|
| You need the size of the effect and its precision | A confidence interval from estimation theory |
| Many hypotheses are tested at once | Adjusted p-values with Bonferroni or false discovery rate control |
| You want evidence for one hypothesis relative to another | A Bayes factor or a posterior probability |
Math foundations
Definition
Written here for an upper-tailed test. is the statistic as a random quantity under the null and is the value you observed. Everything is conditional on the null being true.
One-sided and two-sided forms
is the null cumulative distribution. The two-sided value doubles the smaller tail, which for a symmetric distribution equals the chance of landing at least as far from the centre on either side. For a discrete statistic the tails include the observed value itself.
Uniform under the null
For a continuous statistic, the p-value of a true null is equally likely to be anywhere between 0 and 1. This is why rejecting when gives a false positive rate of exactly .
Exact permutation p-value
Count the relabellings whose difference of means is at least as extreme as the observed one, and divide by the number of ways to choose which pooled values form the first group. This is the two-sided form.
Random permutation p-value
When there are too many relabellings to list, draw at random. Adding one to the top and bottom counts the observed labelling as one of the draws, which keeps the test valid and means the p-value is never zero.
Symbols
- the test statistic as a random variable under the null
- the observed value of the statistic
- the null hypothesis
- cumulative distribution function of T under the null
- any threshold between 0 and 1
- sizes of the two samples
- observed difference of means
- difference of means under relabelling pi, or under random relabelling b
- number of random relabellings, n_resamples in the template
Worked by hand
Part one: a statistic of 2.0, with . Part two: a permutation test with and , observed difference . The pooled values can be split into two pairs in 6 ways.
The statistic gives a two-sided p-value of 0.0455. In the permutation test the observed split is the most extreme one possible, yet the p-value is 0.333, because with only six relabellings no smaller two-sided value exists.
Visual example
Loading the example.
Try this
- Set the true difference to 0 and watch the observed line fall in the middle of the pile.
- Drop to 2 values per group: there are only 6 relabellings, so p cannot go below 0.333 two-sided.
- Switch the alternative to less while the difference is positive, and see p jump toward 1.
Code sample
from impl import PValue
from config import PValueConfig
print(PValue(PValueConfig(distribution="t", df=10)).from_statistic(2.228)) # 0.05
print(PValue(PValueConfig(distribution="chi2", df=1, alternative="greater")).from_statistic(3.841)) # 0.05
print(PValue().permutation_test([1, 2, 3], [4, 5, 6])) # exact, p = 0.1Read the implementation (197 lines)
"""The p-value: tail probabilities of the common null distributions, and a permutation test.
NumPy and the standard library only. The normal, Student t, chi-square and F distribution functions are
computed in this file from the regularized incomplete beta and gamma functions.
"""
from __future__ import annotations
import itertools
import math
import numpy as np
try:
from .config import PValueConfig
except ImportError: # run from the template's own folder
from config import PValueConfig
def _betacf(a: float, b: float, x: float) -> float:
"""Continued fraction of the incomplete beta function (modified Lentz method)."""
tiny = 1e-300
qab, qap, qam = a + b, a + 1.0, a - 1.0
c = 1.0
d = 1.0 - qab * x / qap
d = 1.0 / (d if abs(d) > tiny else tiny)
h = d
for m in range(1, 2000):
m2 = 2 * m
for aa in (
m * (b - m) * x / ((qam + m2) * (a + m2)),
-(a + m) * (qab + m) * x / ((a + m2) * (qap + m2)),
):
d = 1.0 + aa * d
d = 1.0 / (d if abs(d) > tiny else tiny)
c = 1.0 + aa / c
c = c if abs(c) > tiny else tiny
delta = d * c
h *= delta
if abs(delta - 1.0) < 1e-15:
break
return h
def betainc(a: float, b: float, x: float) -> float:
"""Regularized incomplete beta function I_x(a, b), for a, b > 0 and 0 <= x <= 1."""
if x <= 0.0:
return 0.0
if x >= 1.0:
return 1.0
front = math.exp(
math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log1p(-x)
)
if x < (a + 1.0) / (a + b + 2.0):
return front * _betacf(a, b, x) / a
return 1.0 - front * _betacf(b, a, 1.0 - x) / b
def gammaincc(a: float, x: float) -> float:
"""Regularized upper incomplete gamma function Q(a, x) = 1 - P(a, x), for a > 0 and x >= 0."""
if x <= 0.0:
return 1.0
log_front = a * math.log(x) - x - math.lgamma(a)
if x < a + 1.0: # series for P
term = total = 1.0 / a
n = a
for _ in range(10000):
n += 1.0
term *= x / n
total += term
if abs(term) < abs(total) * 1e-16:
break
return 1.0 - total * math.exp(log_front)
tiny = 1e-300 # continued fraction for Q (modified Lentz method)
b = x + 1.0 - a
c = 1.0 / tiny
d = 1.0 / b
h = d
for i in range(1, 10000):
an = -i * (i - a)
b += 2.0
d = an * d + b
d = 1.0 / (d if abs(d) > tiny else tiny)
c = b + an / c
c = c if abs(c) > tiny else tiny
delta = d * c
h *= delta
if abs(delta - 1.0) < 1e-15:
break
return h * math.exp(log_front)
def norm_cdf(z: float) -> float:
"""P(Z <= z) for a standard normal Z."""
return 0.5 * math.erfc(-z / math.sqrt(2.0))
def norm_sf(z: float) -> float:
"""P(Z > z) for a standard normal Z (the upper tail)."""
return 0.5 * math.erfc(z / math.sqrt(2.0))
def t_cdf(t: float, df: float) -> float:
"""P(T <= t) for Student's t with `df` degrees of freedom."""
tail = 0.5 * betainc(0.5 * df, 0.5, df / (df + t * t))
return 1.0 - tail if t > 0 else tail
def t_sf(t: float, df: float) -> float:
"""P(T > t) for Student's t with `df` degrees of freedom."""
return t_cdf(-t, df)
def chi2_sf(x: float, df: float) -> float:
"""P(X > x) for a chi-square variable with `df` degrees of freedom."""
return gammaincc(0.5 * df, 0.5 * x) if x > 0 else 1.0
def chi2_cdf(x: float, df: float) -> float:
"""P(X <= x) for a chi-square variable with `df` degrees of freedom."""
return 1.0 - chi2_sf(x, df)
def f_sf(f: float, df1: float, df2: float) -> float:
"""P(F > f) for an F variable with (`df1`, `df2`) degrees of freedom."""
if f <= 0.0:
return 1.0
return betainc(0.5 * df2, 0.5 * df1, df2 / (df2 + df1 * f))
def f_cdf(f: float, df1: float, df2: float) -> float:
"""P(F <= f) for an F variable with (`df1`, `df2`) degrees of freedom."""
return 1.0 - f_sf(f, df1, df2)
class PValue:
"""Converts an observed test statistic into a p-value."""
def __init__(self, config: PValueConfig | None = None) -> None:
self.config = config or PValueConfig()
def tail_probabilities(self, statistic: float) -> tuple[float, float]:
"""(P(T <= statistic), P(T >= statistic)) under the configured null distribution."""
c = self.config
if c.distribution == "z":
return norm_cdf(statistic), norm_sf(statistic)
if c.distribution == "t":
return t_cdf(statistic, c.df), t_sf(statistic, c.df)
if c.distribution == "chi2":
upper = chi2_sf(statistic, c.df)
else:
upper = f_sf(statistic, c.df, c.df2)
return 1.0 - upper, upper
def from_statistic(self, statistic: float) -> float:
"""The p-value of an observed statistic.
`greater` returns the upper tail, `less` the lower tail, and `two-sided` twice the smaller tail
(capped at 1). For chi-square and F statistics, which grow with any departure from the null,
the usual choice is `greater`.
"""
lower, upper = self.tail_probabilities(float(statistic))
if self.config.alternative == "greater":
return upper
if self.config.alternative == "less":
return lower
return min(1.0, 2.0 * min(lower, upper))
def permutation_test(self, x, y) -> dict:
"""p-value for "x and y come from the same distribution", using the difference of means.
x: (n1,), y: (n2,). Under the null the group labels are exchangeable, so the observed difference
is compared with the differences obtained by relabelling the pooled values. Returns `statistic`
(mean(x) - mean(y)), `p_value`, `exact` (True when every relabelling was listed) and
`n_relabellings`. The random version counts the observed labelling as one of the relabellings,
so its p-value is never zero.
"""
x, y = np.asarray(x, dtype=float).ravel(), np.asarray(y, dtype=float).ravel()
n1, n = x.size, x.size + y.size
if n1 == 0 or y.size == 0:
raise ValueError("both samples need at least one value")
pooled = np.concatenate([x, y])
total = pooled.sum()
observed = float(x.mean() - y.mean())
def difference(first_sum: np.ndarray) -> np.ndarray:
return first_sum / n1 - (total - first_sum) / (n - n1)
exact = math.comb(n, n1) <= self.config.n_resamples
if exact:
sums = np.array([pooled[list(idx)].sum() for idx in itertools.combinations(range(n), n1)])
else:
rng = np.random.default_rng(self.config.seed)
sums = np.array([rng.permutation(pooled)[:n1].sum() for _ in range(self.config.n_resamples)])
diffs = difference(sums)
tol = 1e-12 * max(1.0, abs(observed))
if self.config.alternative == "greater":
extreme = diffs >= observed - tol
elif self.config.alternative == "less":
extreme = diffs <= observed + tol
else:
extreme = np.abs(diffs) >= abs(observed) - tol
count = int(np.sum(extreme))
p = count / diffs.size if exact else (count + 1) / (diffs.size + 1)
return {"statistic": observed, "p_value": p, "exact": exact, "n_relabellings": int(diffs.size)}- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Use PValue(PValueConfig(distribution="z")) and call from_statistic(2.0), then repeat with distribution="t" and df set to 5, 30 and 1000. Call permutation_test([5, 6], [1, 2]) and check the worked example. Finally draw two samples of 30 from the same normal distribution, record the permutation p-value over 200 repeats, and look at its histogram.
Check on learning
- A study reports . A colleague says there is a 97% chance the effect is real. What extra information would you need to say anything about that chance, and why is it missing from the p-value?
A way to think about it
The p-value conditions on the null being true. To get the chance that the null is true given the data, you would need how plausible the null was beforehand and how likely the data are under the alternative.
- If the null hypothesis is true and you repeat an experiment 1000 times, what does the histogram of the 1000 p-values look like, and how many fall below 0.05?
A way to think about it
Use the uniform result. Then ask what that implies about a single small p-value among many tests.
- For the same statistic, why does the distribution with 5 degrees of freedom give a larger p-value than the normal distribution?
A way to think about it
Compare the tails. A distribution with more mass far from zero treats a given large value as less surprising.
- With samples of sizes 3 and 3, what is the smallest two-sided permutation p-value possible? What does that mean for testing at ?
A way to think about it
Count the relabellings, then note that the mirror image of the most extreme split is as extreme as the split itself.