Overview
You start with a default claim, the null hypothesis , such as 'the mean is 50' or 'the two groups have the same mean'. The alternative is what you suspect instead. You then ask: if were true, how unusual would data like mine be? A test statistic measures the gap between the sample and the claim in units of standard error. The p-value turns that gap into a probability. If it falls below a threshold chosen in advance, you reject . Otherwise you fail to reject it, which is not the same as showing it true. The logic is like a trial: the null is presumed to hold until the evidence against it is strong.
A short history
Karl Pearson's chi-square test of 1900 and William Gosset's t test of 1908 were early examples. Ronald Fisher built significance testing into a general method in Statistical Methods for Research Workers in 1925, treating the p-value as a measure of evidence against a null hypothesis. Jerzy Neyman and Egon Pearson reframed it in 1933 as a decision between a null and an alternative with controlled error rates. Present practice is a blend of both views.
How it works
- State with an equals sign and choose as
two-sided,lessorgreaterbefore seeing the data. - Fix the significance level , the rate of false rejections you accept.
- Pick the test for your design: a test when is known, a test when it is estimated, paired or two-sample as the data require, or a proportion test.
- Compute the test statistic: the estimate minus the null value, divided by its standard error.
- Compute the p-value from the null distribution of the statistic, using the tail or tails that points to.
- Reject when , and report the statistic, degrees of freedom and p-value along with the decision.
Watch out for
- Failing to reject does not prove the null hypothesis. A small sample may simply lack the power to detect a real difference.
- Choosing the direction of a one-sided alternative after looking at the data doubles the real false positive rate.
- Using the two-sample test on paired data throws away the pairing and usually loses power, while using the paired test on unpaired data is simply wrong.
- The pooled two-sample test assumes equal variances. When that fails and group sizes differ its p-values are off, so the template defaults to Welch's test.
- Statistical significance is not practical importance: with enough data a negligible effect yields a tiny p-value.
Use cases
When to use it
Deciding whether an observed difference, such as a change in a mean or a rate between two versions, is larger than sampling noise alone would produce.
In industry
- Pharmaceuticals
- Drug regulators require trials that test the null hypothesis of no treatment effect at a prespecified significance level before approval.
- Technology
- Product teams run A/B tests in which the null hypothesis says a new design leaves the conversion rate unchanged.
- Manufacturing
- Acceptance sampling tests whether a batch meets its specification from a sample of items.
Choosing it: what must hold
- A null and an alternative hypothesis stated before looking at the data.
- A test whose assumptions about independence, distribution and sample size match how the data were collected.
- A significance level and, ideally, a sample size chosen in advance from a power calculation.
- A random sample or a randomised experiment, so that probability statements are justified.
When to choose something else
| If | Use instead |
|---|---|
| You want to know how large an effect is, not only whether it exists | Estimation theory, reporting a confidence interval |
| You want the probability that a hypothesis is true given the data | Bayesian analysis |
| The test's distribution assumptions do not hold | A permutation test or another nonparametric test |
Math foundations
The two hypotheses
The null fixes the parameter at one value so that the statistic's distribution is known. The alternative is two-sided or one-sided, and that choice decides which tail counts as evidence.
The z statistic
The distance from the sample mean to the null value in standard errors, when the population standard deviation is known. For a proportion the same form holds with , and standard error .
The t statistic
When is replaced by the sample value , the extra uncertainty gives the statistic heavier tails: Student's with degrees of freedom. The paired test is this test applied to the differences.
Welch's two-sample t
For two independent samples the variances of the two means add. The degrees of freedom come from the Welch-Satterthwaite formula and are usually not a whole number. With
equal_var: truea pooled variance and degrees of freedom are used instead.The decision rule
is the cumulative distribution of the statistic under the null. The p-value is the probability, under , of a statistic at least as extreme as the one observed, in the direction names.
Symbols
- null and alternative hypotheses
- true population mean and the value the null claims
- sample mean, sample standard deviation, sample size
- known population standard deviation
- difference of means claimed by the null, usually 0
- degrees of freedom of Welch's test
- sample proportion and the proportion the null claims
- cumulative distribution function of the statistic under the null
- p-value and significance level
Worked by hand
Sample . Test against the two-sided alternative at . The sample has , and . The table gives .
Fail to reject . The sample mean is 3 above the claimed value, but with five observations that gap is only 2.12 standard errors, which happens by chance about one time in ten.
Visual example
Loading the example.
Try this
- Click each step of the diagram in order and read what it holds.
- Type the sample twice over (4, 6, 8, 10, 12, 4, 6, 8, 10, 12). The same mean now rejects H₀.
- Switch the alternative to greater and compare the p-value with the two-sided one.
Code sample
import numpy as np
from impl import HypothesisTest
from config import HypothesisTestingConfig
rng = np.random.default_rng(0)
x = rng.normal(5.4, 1.0, 25)
result = HypothesisTest(HypothesisTestingConfig(alpha=0.05, alternative="greater")).one_sample_t(x, mu0=5.0)
print(result["null"], "|", result["alternative"])
print(result["statistic"], result["p_value"], result["conclusion"])Read the implementation (156 lines)
"""Hypothesis testing: null against alternative for means and proportions.
NumPy and the standard library only. The normal and Student t distribution functions are computed in this
file (the t distribution through the regularized incomplete beta function).
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import HypothesisTestingConfig
except ImportError: # run from the template's own folder
from config import HypothesisTestingConfig
_SYMBOL = {"two-sided": "!=", "less": "<", "greater": ">"}
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 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)
class HypothesisTest:
"""z and t tests. Every method returns the same kind of result dict (see `_result`)."""
def __init__(self, config: HypothesisTestingConfig | None = None) -> None:
self.config = config or HypothesisTestingConfig()
def _result(self, name: str, quantity: str, null_value: float, statistic: float, df: float | None) -> dict:
"""Turn a test statistic into a decision.
df: degrees of freedom of the t distribution, or None for a z statistic.
Returns `test`, `null`, `alternative` (the two hypotheses in words), `statistic`, `df`, `p_value`,
`reject` (p < alpha) and `conclusion`.
"""
cdf = norm_cdf(statistic) if df is None else t_cdf(statistic, df)
sf = norm_cdf(-statistic) if df is None else t_cdf(-statistic, df)
alt = self.config.alternative
p = {"two-sided": min(1.0, 2.0 * min(cdf, sf)), "less": cdf, "greater": sf}[alt]
reject = p < self.config.alpha
verdict = "reject the null hypothesis" if reject else "fail to reject the null hypothesis"
return {
"test": name,
"null": f"H0: {quantity} = {null_value:g}",
"alternative": f"H1: {quantity} {_SYMBOL[alt]} {null_value:g}",
"statistic": statistic, "df": df, "p_value": p, "reject": reject,
"conclusion": f"p = {p:.4g} against alpha = {self.config.alpha:g}: {verdict}",
}
def one_sample_z(self, x, mu0: float, sigma: float) -> dict:
"""Mean of x (n,) against mu0 when the population standard deviation `sigma` is known."""
x = np.asarray(x, dtype=float).ravel()
if sigma <= 0:
raise ValueError("sigma must be positive")
z = (float(x.mean()) - mu0) / (sigma / math.sqrt(x.size))
return self._result("one-sample z", "mean", mu0, z, None)
def one_sample_t(self, x, mu0: float) -> dict:
"""Mean of x (n,) against mu0, with the standard deviation estimated from the sample."""
x = np.asarray(x, dtype=float).ravel()
if x.size < 2:
raise ValueError("need at least 2 observations")
t = (float(x.mean()) - mu0) / (float(x.std(ddof=1)) / math.sqrt(x.size))
return self._result("one-sample t", "mean", mu0, t, x.size - 1.0)
def paired_t(self, x, y, diff0: float = 0.0) -> dict:
"""Mean of the paired differences x - y against diff0. x and y have the same shape (n,)."""
x, y = np.asarray(x, dtype=float).ravel(), np.asarray(y, dtype=float).ravel()
if x.size != y.size:
raise ValueError("paired samples must have the same length")
out = self.one_sample_t(x - y, diff0)
out.update(test="paired t", null=out["null"].replace("mean", "mean difference"),
alternative=out["alternative"].replace("mean", "mean difference"))
return out
def two_sample_t(self, x, y, diff0: float = 0.0) -> dict:
"""Mean of x (n1,) minus mean of y (n2,) against diff0, for two independent samples."""
x, y = np.asarray(x, dtype=float).ravel(), np.asarray(y, dtype=float).ravel()
n1, n2 = x.size, y.size
if n1 < 2 or n2 < 2:
raise ValueError("need at least 2 observations in each sample")
v1, v2 = float(x.var(ddof=1)), float(y.var(ddof=1))
diff = float(x.mean() - y.mean()) - diff0
if self.config.equal_var:
df = n1 + n2 - 2.0
pooled = ((n1 - 1) * v1 + (n2 - 1) * v2) / df
t = diff / math.sqrt(pooled * (1.0 / n1 + 1.0 / n2))
name = "two-sample t (pooled)"
else:
a, b = v1 / n1, v2 / n2
t = diff / math.sqrt(a + b)
df = (a + b) ** 2 / (a * a / (n1 - 1) + b * b / (n2 - 1)) # Welch-Satterthwaite
name = "two-sample t (Welch)"
return self._result(name, "difference of means", diff0, t, df)
def proportion_z(self, successes: int, n: int, p0: float) -> dict:
"""Proportion `successes / n` against p0, with the normal approximation to the binomial."""
if n <= 0 or not 0 <= successes <= n:
raise ValueError("need n > 0 and 0 <= successes <= n")
if not 0.0 < p0 < 1.0:
raise ValueError("p0 must be in (0, 1)")
z = (successes / n - p0) / math.sqrt(p0 * (1.0 - p0) / n)
return self._result("one-proportion z", "proportion", p0, z, None)- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 9, run with
python3 -m unittest -v
Practice
Run HypothesisTest().one_sample_t(x, 5) on the worked sample and read statistic, p_value and conclusion. Repeat with HypothesisTestingConfig(alternative="greater"). Then build two samples with different spreads and sizes and compare two_sample_t with equal_var false and true.
Check on learning
- In the worked example the two-sided p-value is about 0.10 and the one-sided p-value for
greateris about 0.05, exactly half. Why half, and which of the two should be reported?A way to think about it
The distribution is symmetric, so one tail holds half of the two-tail probability. Then ask what you would have concluded had the sample mean come out 3 below the null value, and whether the direction was fixed before the data arrived.
- Why is the conclusion worded 'fail to reject' instead of 'accept' the null hypothesis?
A way to think about it
Consider testing and then on the same small sample. If neither is rejected, can both be accepted as true?
- A before-and-after study measures the same 20 people twice. How would the p-value from
two_sample_tusually compare with the one frompaired_t, and why?A way to think about it
People differ a lot from each other. Decide which test's standard error contains that person-to-person spread and which one cancels it.
- As grows, the test and the test give nearly the same p-value. What is it about the distribution that makes the difference fade?
A way to think about it
The heavier tails pay for uncertainty in . Think about how well pins down when the sample is large.