Sign in

Test statistics

Z, t and chi-square test statistics

Three families of numbers that measure how far data sit from a null hypothesis: z and t for means and proportions, chi-square for counts.

Overview

A test statistic compresses a whole sample into one number that says how far the data are from what the null hypothesis predicts. The zz and tt statistics share one pattern: an observed value minus the expected value, divided by a standard error, so they count standard errors of distance. Use zz when the standard deviation is known or fixed by the null, as with proportions. Use tt when it has to be estimated from the sample, which adds uncertainty and widens the tails. The chi-square statistic is for counts in categories. It adds up, over every category, the squared gap between the observed and expected count relative to the expected count.

A short history

The z statistic rests on the normal approximation of Abraham de Moivre and Pierre-Simon Laplace from the eighteenth and early nineteenth centuries. Karl Pearson introduced the chi-square statistic in 1900 for comparing observed and expected counts. William Sealy Gosset, a brewer at Guinness writing as Student, published the t distribution in 1908 because small samples with an estimated standard deviation do not follow the normal curve. Fisher later put all three in one framework.

How it works

  1. Identify the data type: a mean with known σ\sigma, a mean with unknown σ\sigma, proportions, or counts in categories.
  2. For a mean with known σ\sigma, compute zz as the gap from the null value over σ/n\sigma/\sqrt{n}.
  3. For a mean with unknown σ\sigma, compute tt the same way with the sample standard deviation ss, and note n−1n-1 degrees of freedom.
  4. For two proportions, compute zz from their difference and a standard error built on the pooled proportion.
  5. For counts, compute the expected count of each category under the null and sum (O−E)2/E(O-E)^2/E.
  6. Compare the statistic with its null distribution, normal, tt or chi-square, to get the p-value: two-sided for zz and tt, upper tail for chi-square.

Watch out for

  • Using zz with a standard deviation estimated from a small sample understates the uncertainty and produces p-values that are too small. That case calls for tt.
  • The chi-square approximation is poor when expected counts are small, with a common rule asking for at least 5 in every cell.
  • The chi-square statistic must be computed on raw counts. Feeding it percentages or proportions gives a number on the wrong scale.
  • A chi-square test of independence says that two variables are associated, not how strongly or in which cells, so inspect observed against expected counts.
  • The tt statistic assumes roughly normal data or a sample large enough for the mean to be near normal. Strong outliers in a small sample distort both the mean and ss.

Use cases

When to use it

Choosing and computing the right statistic for a test: z or t for one or two means, z for proportions, and chi-square for goodness of fit or for independence in a table of counts.

In industry

Brewing and manufacturing
Small batch quality checks compare a sample mean with a target using the t statistic, the purpose for which Gosset developed it at Guinness.
Online experimentation
A/B tests on conversion rates with large samples use a z statistic for the difference between two proportions.
Genetics and surveys
Chi-square statistics compare observed counts with expected ones, for example offspring ratios against Mendelian predictions or survey answers across groups.

Choosing it: what must hold

  • For z, a large sample or a known population standard deviation, and a mean or proportion as the target.
  • For t, a numeric outcome that is roughly normal, with the standard deviation estimated from the sample.
  • For chi-square, counts of independent observations in categories, with expected counts of about five or more.
  • Independent observations in every case, unless a paired version of the test is used.

When to choose something else

IfUse instead
Three or more group means are comparedOne-way ANOVA
Expected counts are small in a 2 by 2 tableFisher's exact test
The data are ordinal or far from normal with a small sampleA rank test such as Mann-Whitney or Wilcoxon signed rank

Math foundations

  1. The z statistic

    z=xˉ−μ0σ/nz = \frac{\bar{x}-\mu_0}{\sigma/\sqrt{n}}

    The gap between the sample mean and the null value, in standard errors, when σ\sigma is known. Under the null it follows the standard normal distribution.

  2. The t statistic

    t=xˉ−μ0s/n,df=n−1t = \frac{\bar{x}-\mu_0}{s/\sqrt{n}}, \qquad \text{df} = n-1

    The same ratio with the sample standard deviation ss in place of σ\sigma. Under the null it follows Student's tt, which has heavier tails than the normal and approaches it as nn grows.

  3. Two-proportion z

    z=p^1−p^2p^(1−p^)(1n1+1n2),p^=x1+x2n1+n2z = \frac{\hat{p}_1-\hat{p}_2}{\sqrt{\hat{p}(1-\hat{p})\left(\dfrac{1}{n_1}+\dfrac{1}{n_2}\right)}}, \qquad \hat{p} = \frac{x_1+x_2}{n_1+n_2}

    Under the null the two groups share one proportion, so the best estimate of it pools both groups. The variance of a proportion depends only on that proportion, which is why zz and not tt is used.

  4. Chi-square goodness of fit

    χ2=∑i=1k(Oi−Ei)2Ei,df=k−1\chi^2 = \sum_{i=1}^{k}\frac{(O_i-E_i)^2}{E_i}, \qquad \text{df} = k-1

    Each term is a squared gap scaled by the expected count, so a miss of 10 matters more when 20 were expected than when 2000 were. One degree of freedom is lost because the counts must add to the total.

  5. Chi-square test of independence

    Eij=Ri CjN,χ2=∑i=1r∑j=1c(Oij−Eij)2Eij,df=(r−1)(c−1)E_{ij} = \frac{R_i\,C_j}{N}, \qquad \chi^2 = \sum_{i=1}^{r}\sum_{j=1}^{c}\frac{(O_{ij}-E_{ij})^2}{E_{ij}}, \qquad \text{df} = (r-1)(c-1)

    If rows and columns are independent, the chance of landing in a cell is the product of its row share and column share, which gives the expected count. With yates_correction on, a 2 x 2 table has 0.5 subtracted from each absolute gap before squaring.

Symbols

xˉ, s, n\bar{x},\ s,\ n
sample mean, sample standard deviation and sample size
μ0\mu_0
the mean claimed by the null hypothesis
σ\sigma
known population standard deviation
p^1, p^2\hat{p}_1,\ \hat{p}_2
sample proportions of the two groups
x1, x2x_1,\ x_2
numbers of successes in the two groups
n1, n2n_1,\ n_2
sizes of the two groups
p^\hat{p}
pooled proportion
Oi, EiO_i,\ E_i
observed and expected count in category i
kk
number of categories
Oij, EijO_{ij},\ E_{ij}
observed and expected count in row i, column j
Ri, Cj, NR_i,\ C_j,\ N
row total, column total and grand total of the table
r, cr,\ c
numbers of rows and columns

Worked by hand

A 2 x 2 table of counts: row 1 is (30,10)(30, 10) and row 2 is (20,40)(20, 40). Row totals are 40 and 60, column totals are 50 and 50, and N=100N = 100.

E11=40⋅50100=20,E12=20,E21=60⋅50100=30,E22=30E_{11} = \frac{40\cdot 50}{100} = 20, \quad E_{12} = 20, \quad E_{21} = \frac{60\cdot 50}{100} = 30, \quad E_{22} = 30
χ2=(30−20)220+(10−20)220+(20−30)230+(40−30)230\chi^2 = \frac{(30-20)^2}{20}+\frac{(10-20)^2}{20}+\frac{(20-30)^2}{30}+\frac{(40-30)^2}{30}
χ2=5+5+3.33+3.33=16.67,df=(2−1)(2−1)=1\chi^2 = 5 + 5 + 3.33 + 3.33 = 16.67, \qquad \text{df} = (2-1)(2-1) = 1

The statistic 16.67 is far above 3.84, the 5% critical value of chi-square with 1 degree of freedom, so the rows and columns are not independent.

Visual example

Loading the example.

Try this

  • With the same numbers, switch from z to t and compare the critical values and the p-values.
  • Raise the sample size and watch the same gap in the mean become more standard errors.
  • Choose chi-square and move the counts until every observed count equals its expected count.

Code sample

from impl import TestStatistics
from config import TestStatisticsConfig

stats = TestStatistics(TestStatisticsConfig())
print(stats.z_statistic([98, 102, 104, 100], mu0=100, sigma=2))        # z = 1.0
print(stats.t_statistic([3, 4, 5, 6, 7], mu0=3))                       # t = 2.83, df = 4
print(stats.chi_square_goodness_of_fit([16, 18, 16, 14, 12, 12]))      # chi2 = 2.0, df = 5
print(stats.chi_square_independence([[10, 10, 20], [20, 20, 20]]))     # chi2 = 2.78, df = 2
Read the implementation (208 lines)
"""Z, t and chi-square test statistics with their p-values.

NumPy and the standard library only. The normal, Student t and chi-square distribution functions are computed
in this file from the regularized incomplete beta and gamma functions.
"""
from __future__ import annotations

import math

import numpy as np

try:
    from .config import TestStatisticsConfig
except ImportError:  # run from the template's own folder
    from config import TestStatisticsConfig

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)

class TestStatistics:
    """Each method returns a dict with `statistic`, `df` (None for z) and the two-sided or upper `p_value`."""

    __test__ = False  # the name starts with "Test" but this is not a test case

    def __init__(self, config: TestStatisticsConfig | None = None) -> None:
        self.config = config or TestStatisticsConfig()

    # ---- z: the sampling distribution is normal with a known standard error ---------------------------
    @staticmethod
    def z_statistic(x, mu0: float, sigma: float) -> dict:
        """z = (mean(x) - mu0) / (sigma / sqrt(n)), for a sample x (n,) with known population sigma."""
        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 {"statistic": z, "df": None, "p_value": 2.0 * norm_sf(abs(z))}

    @staticmethod
    def z_proportions(successes1: int, n1: int, successes2: int, n2: int) -> dict:
        """z statistic for the difference of two proportions, with the pooled standard error."""
        p1, p2 = successes1 / n1, successes2 / n2
        pooled = (successes1 + successes2) / (n1 + n2)
        se = math.sqrt(pooled * (1.0 - pooled) * (1.0 / n1 + 1.0 / n2))
        if se == 0:
            raise ValueError("the pooled proportion is 0 or 1, the statistic is undefined")
        z = (p1 - p2) / se
        return {"statistic": z, "df": None, "p_value": 2.0 * norm_sf(abs(z))}

    # ---- t: the standard error is estimated from the sample ------------------------------------------
    @staticmethod
    def t_statistic(x, mu0: float) -> dict:
        """t = (mean(x) - mu0) / (s / sqrt(n)) with n - 1 degrees of freedom, for a sample x (n,)."""
        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))
        df = x.size - 1.0
        return {"statistic": t, "df": df, "p_value": 2.0 * t_sf(abs(t), df)}

    def t_two_sample(self, x, y) -> dict:
        """t statistic for the difference of the means of two independent samples x (n1,) and y (n2,)."""
        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())
        if self.config.equal_var:
            df = n1 + n2 - 2.0
            t = diff / math.sqrt(((n1 - 1) * v1 + (n2 - 1) * v2) / df * (1.0 / n1 + 1.0 / n2))
        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))
        return {"statistic": t, "df": df, "p_value": 2.0 * t_sf(abs(t), df)}

    # ---- chi-square: observed counts against expected counts ----------------------------------------
    @staticmethod
    def chi_square_goodness_of_fit(observed, expected=None) -> dict:
        """Sum of (observed - expected)^2 / expected over k categories, with k - 1 degrees of freedom.

        observed: counts, shape (k,). expected: counts, shape (k,), with the same total; when None, all
        categories are taken as equally likely.
        """
        obs = np.asarray(observed, dtype=float).ravel()
        exp = np.full(obs.size, obs.sum() / obs.size) if expected is None else np.asarray(expected, dtype=float).ravel()
        if exp.shape != obs.shape or np.any(exp <= 0):
            raise ValueError("expected must be positive and have the same shape as observed")
        if abs(exp.sum() - obs.sum()) > 1e-8 * obs.sum():
            raise ValueError("observed and expected counts must have the same total")
        stat = float(np.sum((obs - exp) ** 2 / exp))
        df = obs.size - 1.0
        return {"statistic": stat, "df": df, "p_value": chi2_sf(stat, df), "expected": exp}

    def chi_square_independence(self, table) -> dict:
        """Chi-square test that the row and column variables of a contingency table are independent.

        table: counts, shape (r, c). Expected counts are row total * column total / grand total, and the
        degrees of freedom are (r - 1)(c - 1).
        """
        obs = np.asarray(table, dtype=float)
        if obs.ndim != 2 or min(obs.shape) < 2:
            raise ValueError("table must have at least 2 rows and 2 columns")
        exp = np.outer(obs.sum(axis=1), obs.sum(axis=0)) / obs.sum()
        if np.any(exp <= 0):
            raise ValueError("every row and column needs a positive total")
        gap = np.abs(obs - exp)
        if self.config.yates_correction and obs.shape == (2, 2):
            gap = np.maximum(gap - 0.5, 0.0)
        stat = float(np.sum(gap**2 / exp))
        df = float((obs.shape[0] - 1) * (obs.shape[1] - 1))
        return {"statistic": stat, "df": df, "p_value": chi2_sf(stat, df), "expected": exp}
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Call TestStatistics().chi_square_independence([[30, 10], [20, 40]]) and check statistic and expected, then repeat with TestStatisticsConfig(yates_correction=True). For one small sample, compare the p_value of TestStatistics.z_statistic(x, mu0, sigma), with sigma set to the sample standard deviation, against TestStatistics.t_statistic(x, mu0).

Check on learning

  1. For the same sample, same null value and σ\sigma set equal to ss, the zz and tt statistics are the same number. Why are their p-values different, and which is larger?
    A way to think about it

    The statistic is identical. What differs is the reference distribution, so compare the tails of the two.

  2. The two-proportion statistic pools the two samples to estimate the standard error. Why is pooling justified for a test, and would you pool when building a confidence interval for the difference?
    A way to think about it

    A test works under the assumption that the null is true. An interval makes no such assumption about the two proportions being equal.

  3. If every count in a contingency table is multiplied by 10, what happens to the chi-square statistic and what does that say about using it as a measure of how strong an association is?
    A way to think about it

    Follow the factor of 10 through (O−E)2/E(O-E)^2/E. The pattern of proportions in the table has not changed at all.

  4. Why does a goodness-of-fit test with kk categories have k−1k-1 degrees of freedom and not kk?
    A way to think about it

    Once the total is fixed, ask how many of the kk gaps Oi−EiO_i - E_i are free to vary before the last one is forced.