Sign in

Hypothesis testing

Statistical hypothesis testing

A procedure that decides whether data are compatible with a default claim, the null hypothesis, by measuring how surprising they would be if that claim were true.

Overview

You start with a default claim, the null hypothesis H0H_0, such as 'the mean is 50' or 'the two groups have the same mean'. The alternative H1H_1 is what you suspect instead. You then ask: if H0H_0 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 α\alpha chosen in advance, you reject H0H_0. 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

  1. State H0H_0 with an equals sign and choose H1H_1 as two-sided, less or greater before seeing the data.
  2. Fix the significance level α\alpha, the rate of false rejections you accept.
  3. Pick the test for your design: a zz test when σ\sigma is known, a tt test when it is estimated, paired or two-sample as the data require, or a proportion zz test.
  4. Compute the test statistic: the estimate minus the null value, divided by its standard error.
  5. Compute the p-value from the null distribution of the statistic, using the tail or tails that H1H_1 points to.
  6. Reject H0H_0 when p<αp < \alpha, 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

IfUse instead
You want to know how large an effect is, not only whether it existsEstimation theory, reporting a confidence interval
You want the probability that a hypothesis is true given the dataBayesian analysis
The test's distribution assumptions do not holdA permutation test or another nonparametric test

Math foundations

  1. The two hypotheses

    H0: μ=μ0againstH1: μ≠μ0,  μ<μ0  or  μ>μ0H_0:\ \mu = \mu_0 \qquad \text{against} \qquad H_1:\ \mu \ne \mu_0,\ \ \mu < \mu_0 \ \ \text{or}\ \ \mu > \mu_0

    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.

  2. The z statistic

    z=xˉ−μ0σ/n∼N(0,1)under H0z = \frac{\bar{x}-\mu_0}{\sigma/\sqrt{n}} \sim N(0,1) \quad \text{under } H_0

    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 p^\hat{p}, p0p_0 and standard error p0(1−p0)/n\sqrt{p_0(1-p_0)/n}.

  3. The t statistic

    t=xˉ−μ0s/n∼tn−1under H0t = \frac{\bar{x}-\mu_0}{s/\sqrt{n}} \sim t_{n-1} \quad \text{under } H_0

    When σ\sigma is replaced by the sample value ss, the extra uncertainty gives the statistic heavier tails: Student's tt with n−1n-1 degrees of freedom. The paired test is this test applied to the differences.

  4. Welch's two-sample t

    t=(xˉ1−xˉ2)−δ0s12n1+s22n2,ν=(s12n1+s22n2)2(s12/n1)2n1−1+(s22/n2)2n2−1t = \frac{(\bar{x}_1-\bar{x}_2)-\delta_0}{\sqrt{\dfrac{s_1^2}{n_1}+\dfrac{s_2^2}{n_2}}}, \qquad \nu = \frac{\left(\dfrac{s_1^2}{n_1}+\dfrac{s_2^2}{n_2}\right)^{2}}{\dfrac{(s_1^2/n_1)^2}{n_1-1}+\dfrac{(s_2^2/n_2)^2}{n_2-1}}

    For two independent samples the variances of the two means add. The degrees of freedom ν\nu come from the Welch-Satterthwaite formula and are usually not a whole number. With equal_var: true a pooled variance and n1+n2−2n_1+n_2-2 degrees of freedom are used instead.

  5. The decision rule

    reject H0  ⟺  p<α,p={2min⁡{F(t), 1−F(t)}two-sidedF(t)less1−F(t)greater\text{reject } H_0 \iff p < \alpha, \qquad p = \begin{cases} 2\min\{F(t),\,1-F(t)\} & \text{two-sided} \\ F(t) & \text{less} \\ 1-F(t) & \text{greater} \end{cases}

    FF is the cumulative distribution of the statistic under the null. The p-value is the probability, under H0H_0, of a statistic at least as extreme as the one observed, in the direction H1H_1 names.

Symbols

H0, H1H_0,\ H_1
null and alternative hypotheses
μ, μ0\mu,\ \mu_0
true population mean and the value the null claims
xˉ, s, n\bar{x},\ s,\ n
sample mean, sample standard deviation, sample size
σ\sigma
known population standard deviation
δ0\delta_0
difference of means claimed by the null, usually 0
ν\nu
degrees of freedom of Welch's test
p^, p0\hat{p},\ p_0
sample proportion and the proportion the null claims
FF
cumulative distribution function of the statistic under the null
p, αp,\ \alpha
p-value and significance level

Worked by hand

Sample 4,6,8,10,124, 6, 8, 10, 12. Test H0:μ=5H_0: \mu = 5 against the two-sided alternative at α=0.05\alpha = 0.05. The sample has xˉ=8\bar{x}=8, s2=10s^2 = 10 and n=5n=5. The table gives t0.975, 4=2.776t_{0.975,\,4} = 2.776.

SE=105=1.414SE = \sqrt{\frac{10}{5}} = 1.414
t=8−51.414=2.12,df=5−1=4t = \frac{8-5}{1.414} = 2.12, \qquad \text{df} = 5-1 = 4
∣t∣=2.12<2.776 ⇒ p≈0.10>0.05\lvert t\rvert = 2.12 < 2.776 \ \Rightarrow\ p \approx 0.10 > 0.05

Fail to reject H0H_0. 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

  1. In the worked example the two-sided p-value is about 0.10 and the one-sided p-value for greater is about 0.05, exactly half. Why half, and which of the two should be reported?
    A way to think about it

    The tt 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.

  2. Why is the conclusion worded 'fail to reject' instead of 'accept' the null hypothesis?
    A way to think about it

    Consider testing μ=5\mu = 5 and then μ=6\mu = 6 on the same small sample. If neither is rejected, can both be accepted as true?

  3. A before-and-after study measures the same 20 people twice. How would the p-value from two_sample_t usually compare with the one from paired_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.

  4. As nn grows, the tt test and the zz test give nearly the same p-value. What is it about the tt distribution that makes the difference fade?
    A way to think about it

    The heavier tails pay for uncertainty in ss. Think about how well ss pins down σ\sigma when the sample is large.