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 and statistics share one pattern: an observed value minus the expected value, divided by a standard error, so they count standard errors of distance. Use when the standard deviation is known or fixed by the null, as with proportions. Use 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
- Identify the data type: a mean with known , a mean with unknown , proportions, or counts in categories.
- For a mean with known , compute as the gap from the null value over .
- For a mean with unknown , compute the same way with the sample standard deviation , and note degrees of freedom.
- For two proportions, compute from their difference and a standard error built on the pooled proportion.
- For counts, compute the expected count of each category under the null and sum .
- Compare the statistic with its null distribution, normal, or chi-square, to get the p-value: two-sided for and , upper tail for chi-square.
Watch out for
- Using with a standard deviation estimated from a small sample understates the uncertainty and produces p-values that are too small. That case calls for .
- 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 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 .
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
| If | Use instead |
|---|---|
| Three or more group means are compared | One-way ANOVA |
| Expected counts are small in a 2 by 2 table | Fisher's exact test |
| The data are ordinal or far from normal with a small sample | A rank test such as Mann-Whitney or Wilcoxon signed rank |
Math foundations
The z statistic
The gap between the sample mean and the null value, in standard errors, when is known. Under the null it follows the standard normal distribution.
The t statistic
The same ratio with the sample standard deviation in place of . Under the null it follows Student's , which has heavier tails than the normal and approaches it as grows.
Two-proportion z
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 and not is used.
Chi-square goodness of fit
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.
Chi-square test of independence
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_correctionon, a 2 x 2 table has 0.5 subtracted from each absolute gap before squaring.
Symbols
- sample mean, sample standard deviation and sample size
- the mean claimed by the null hypothesis
- known population standard deviation
- sample proportions of the two groups
- numbers of successes in the two groups
- sizes of the two groups
- pooled proportion
- observed and expected count in category i
- number of categories
- observed and expected count in row i, column j
- row total, column total and grand total of the table
- numbers of rows and columns
Worked by hand
A 2 x 2 table of counts: row 1 is and row 2 is . Row totals are 40 and 60, column totals are 50 and 50, and .
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 = 2Read 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
- For the same sample, same null value and set equal to , the and 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.
- 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.
- 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 . The pattern of proportions in the table has not changed at all.
- Why does a goodness-of-fit test with categories have degrees of freedom and not ?
A way to think about it
Once the total is fixed, ask how many of the gaps are free to vary before the last one is forced.