Algorithm Search⌘K

Algorithmintro

Pearson's chi-squared goodness-of-fit test

Also called chi-squared goodness-of-fit test, Pearson chi-squared test.

Compares observed category counts with expected counts by the sum of (O - E)^2 / E, which is asymptotically chi-squared under the null.

Time
Θ(k) worst · best
Space
Θ(k) extra
Where
k = the number of categories
Properties
deterministicnot exactofflineiterative
Origin
Karl Pearson, Ronald A. Fisher, Herman Chernoff, Erich L. Lehmann, 1900

Pearson's chi-squared goodness-of-fit test asks whether counts in kk categories agree with a stated set of category probabilities. It compares each observed count OiO_i with the count EiE_i that the null hypothesis expects and adds up (Oi−Ei)2/Ei(O_i - E_i)^2/E_i. Under the null, for large samples, this sum has approximately the chi-square law with k−1k - 1 degrees of freedom, less one for each parameter fitted from the counts. The test is approximate: its size is close to α\alpha only when the expected counts are not too small.

In plain words

Roll a die 60 times. If it is fair, each face should come up about 10 times. You never get exactly 10 of each, so the question is whether the differences are larger than chance would give. For each face, square the difference between what you saw and what you expected, and divide by what you expected, so that a miss of 5 counts more when you expected 10 than when you expected 1000. Add the six numbers. A fair die gives a total near 5 on average. A total of 13.4 happens by chance only about 2% of the time.

The problem

Model. nn independent observations, each falling in one of k≥2k \ge 2 categories. Category ii has probability pip_i. The counts (O1,…,Ok)(O_1, \ldots, O_k) are multinomial with ∑iOi=n\sum_i O_i = n.

Hypotheses. Simple null H0H_0: p=p0p = p^0 for given pi0>0p^0_i > 0. Composite null: p=p(θ)p = p(\theta) for some θ\theta in an ss-dimensional family. The alternative is any other pp. There is no direction: every kind of misfit increases the statistic.

Statistic. With Ei=npi0E_i = n p^0_i (or npi(θ^)n p_i(\hat\theta)),

X2=∑i=1k(Oi−Ei)2Ei.X^2 = \sum_{i = 1}^k \frac{(O_i - E_i)^2}{E_i}.

The likelihood-ratio form is G=2∑iOilog⁡(Oi/Ei)G = 2 \sum_i O_i \log(O_i/E_i), with 0log⁡0=00 \log 0 = 0.

Null distribution. Asymptotic only: as n→∞n \to \infty with p0p^0 fixed, X2X^2 tends to χk−12\chi^2_{k - 1}. If θ\theta is estimated by maximum likelihood from the grouped counts, the limit is χk−1−s2\chi^2_{k - 1 - s}. If θ\theta is estimated from the raw, ungrouped observations, the limit lies between χk−1−s2\chi^2_{k - 1 - s} and χk−12\chi^2_{k - 1} (Chernoff and Lehmann 1954).

Rejection rule and size. Reject when p≤αp \le \alpha, that is when X2≥χ(k−1−s, 1−α)2X^2 \ge \chi^2_{(k - 1 - s,\ 1 - \alpha)}, the upper α\alpha point. The size tends to α\alpha (proved for a simple null). For finite nn the size is not controlled: it can be above or below α\alpha, as the exact computations below show.

P-values. p=P(χk−1−s2>X2)p = P(\chi^2_{k - 1 - s} > X^2), the upper tail only.

Sensitivity and power. Under a fixed alternative p1p^1, the power tends to 1. For alternatives near the null, X2X^2 is approximately noncentral chi-square with noncentrality λ=n∑i(pi1−pi0)2/pi0\lambda = n \sum_i (p^1_i - p^0_i)^2/p^0_i. The test spreads its power over all k−1k - 1 directions, so a test aimed at one kind of departure (a trend over ordered categories, for example) can be much more powerful against that departure.

The algorithm

  1. CHI-SQUARED-GOF(O[1..k], p[1..k], s)
  2. 1n ← O[1] + ... + O[k]
  3. 2for i ← 1 to k do E[i] ← n · p[i]
  4. 3X2 ← Σ (O[i] - E[i])^2 / E[i] ▷ or G ← 2 Σ over O[i] > 0 of O[i] log(O[i] / E[i])
  5. 4df ← k - 1 - s ▷ s = number of parameters fitted from these counts
  6. 5return (X2, df, P(χ²_df > X2))

The caller passes the null probabilities. If parameters were fitted, the caller computes pi(θ^)p_i(\hat\theta) from the grouped counts and passes ss. Line L5 uses chi2_sf from the shared helper module, the regularized upper incomplete gamma function Q(df/2,X2/2)Q(\mathrm{df}/2, X^2/2).

Example

A suspect die. Sixty rolls give the counts 5,8,9,8,10,205, 8, 9, 8, 10, 20 for faces 1 to 6. Each expected count is 10.

face 1 2 3 4 5 6
OiO_i 5 8 9 8 10 20
(Oi−Ei)2/Ei(O_i - E_i)^2/E_i 2.5 0.4 0.1 0.4 0 10

X2=13.4X^2 = 13.4 on 5 degrees of freedom, and p=P(χ52>13.4)=0.0199p = P(\chi^2_5 > 13.4) = 0.0199. The upper 5% point is 11.070511.0705, so the test rejects at α=0.05\alpha = 0.05. Most of the statistic comes from face 6.

Mendel's peas. Mendel's dihybrid cross gave 315 round yellow, 108 round green, 101 wrinkled yellow and 32 wrinkled green seeds, 556 in all. The theory predicts the ratio 9 : 3 : 3 : 1, so the expected counts are 312.75,104.25,104.25,34.75312.75, 104.25, 104.25, 34.75. Then X2=0.4700X^2 = 0.4700 on 3 degrees of freedom and p=0.9254p = 0.9254. The likelihood-ratio statistic gives G=0.4754G = 0.4754 and p=0.9243p = 0.9243. The data agree with the theory.

A fitted parameter. A sample of 1000 people has genotype counts AA=298AA = 298, Aa=489Aa = 489, aa=213aa = 213. Under Hardy-Weinberg equilibrium the genotype probabilities are θ2\theta^2, 2θ(1−θ)2\theta(1 - \theta) and (1−θ)2(1 - \theta)^2 for an unknown allele frequency θ\theta. The maximum likelihood estimate from these counts is θ^=(2⋅298+489)/2000=0.5425\hat\theta = (2 \cdot 298 + 489)/2000 = 0.5425, so the expected counts are 294.31,496.39,209.31294.31, 496.39, 209.31. Then X2=0.2215X^2 = 0.2215. One parameter was fitted, so there are 3−1−1=13 - 1 - 1 = 1 degree of freedom, and p=0.638p = 0.638. With the wrong count of 2 degrees of freedom the p-value would be 0.8950.895.

The tests check these numbers. They also check X2X^2 against exact rational arithmetic for 300 random tables.

Correctness

The full proof is in proofs/correctness.md. Write the counts as a sum of nn iid unit vectors. The scaled vector YY with entries (Oi−Ei)/Ei(O_i - E_i)/\sqrt{E_i} has covariance I−uu⊤I - uu^\top with u=(pi0)iu = (\sqrt{p^0_i})_i, a unit vector. So by the multivariate central limit theorem, YY tends to a normal vector whose covariance is the projection onto the k−1k - 1 dimensional subspace orthogonal to uu. Then X2=∥Y∥2X^2 = \lVert Y \rVert^2 tends to a sum of k−1k - 1 squared independent standard normals, which is χk−12\chi^2_{k - 1}. For k=2k = 2 the statistic is exactly z2z^2, the square of the score statistic of the binomial test. A third-order Taylor bound shows G−X2→0G - X^2 \to 0 in probability, so GG has the same limit, as Wilks's theorem also predicts.

Proof: Under a simple null the Pearson statistic is the squared length of a projected normal vector in the limit, so it tends to chi-square with k - 1 degrees of freedomfull

Model. nn independent observations fall into k≥2k \ge 2 categories. Category ii has probability pi>0p_i > 0, with ∑ipi=1\sum_i p_i = 1. The counts O=(O1,…,Ok)O = (O_1, \ldots, O_k) are multinomial. The simple null hypothesis fixes p=p0p = p^0. Write Ei=npi0E_i = n p^0_i and

X2=∑i=1k(Oi−Ei)2Ei,G=2∑i:Oi>0Oilog⁡OiEi.X^2 = \sum_{i = 1}^k \frac{(O_i - E_i)^2}{E_i}, \qquad G = 2 \sum_{i : O_i > 0} O_i \log \frac{O_i}{E_i}.

Claim 1 (lines L1 to L3 compute the statistics). Line L1 sets n=∑iOin = \sum_i O_i, line L2 sets Ei=npiE_i = n p_i, and line L3 sums the kk terms of X2X^2 or of GG. In GG a cell with Oi=0O_i = 0 contributes 00, which is the limit of olog⁡(o/e)o \log(o/e) as o→0o \to 0. The sum uses math.fsum, so the only rounding is in the terms. Line L4 sets the degrees of freedom to k−1−sk - 1 - s, where ss is the argument fitted, and line L5 returns P(χk−1−s2>X2)P(\chi^2_{k - 1 - s} > X^2) from the regularized upper incomplete gamma function of the helper module. □\square

Claim 2 (the mean and covariance of the counts). Under H0H_0, E[Oi]=Ei\mathbb{E}[O_i] = E_i, Var⁡(Oi)=npi0(1−pi0)\operatorname{Var}(O_i) = n p^0_i (1 - p^0_i) and Cov⁡(Oi,Oj)=−npi0pj0\operatorname{Cov}(O_i, O_j) = -n p^0_i p^0_j for i≠ji \ne j.

Proof. Write O=∑m=1neJmO = \sum_{m = 1}^n e_{J_m}, where JmJ_m is the category of observation mm and eje_j is the jj-th unit vector. The vectors eJme_{J_m} are iid with mean p0p^0. Their second moment is E[eJeJ⊤]=diag⁡(p0)\mathbb{E}[e_J e_J^\top] = \operatorname{diag}(p^0), because eJeJ⊤e_J e_J^\top has a single 1, on the diagonal at (J,J)(J, J). So each has covariance diag⁡(p0)−p0(p0)⊤\operatorname{diag}(p^0) - p^0 (p^0)^\top, and the sum of nn independent copies has nn times this covariance. □\square

Claim 3 (the limit law under a simple null). Under H0H_0, X2X^2 converges in distribution to χk−12\chi^2_{k - 1} as n→∞n \to \infty, with kk and p0p^0 fixed.

Proof. Let D=diag⁡(p0)−1/2D = \operatorname{diag}(p^0)^{-1/2} and Yn=D(O−np0)/nY_n = D (O - n p^0)/\sqrt n, so the ii-th entry is (Oi−Ei)/Ei(O_i - E_i)/\sqrt{E_i} and X2=∥Yn∥2X^2 = \lVert Y_n \rVert^2. By Claim 2, YnY_n is n−1/2n^{-1/2} times a sum of nn iid centred vectors D(eJm−p0)D(e_{J_m} - p^0) with covariance

D(diag⁡(p0)−p0(p0)⊤)D=I−uu⊤,u=(p10,…,pk0)⊤.D \big(\operatorname{diag}(p^0) - p^0 (p^0)^\top\big) D = I - u u^\top, \qquad u = \big(\sqrt{p^0_1}, \ldots, \sqrt{p^0_k}\big)^\top.

The multivariate central limit theorem gives Yn→WY_n \to W in distribution, with W∼N(0,I−uu⊤)W \sim N(0, I - u u^\top). (The multivariate form follows from the one-dimensional form by the Cramér-Wold device: for each fixed vector aa, a⊤Yna^\top Y_n is a normalized sum of iid scalars with variance a⊤(I−uu⊤)aa^\top (I - uu^\top) a.) The map y↦∥y∥2y \mapsto \lVert y \rVert^2 is continuous, so X2→∥W∥2X^2 \to \lVert W \rVert^2 in distribution.

Now find the law of ∥W∥2\lVert W \rVert^2. Since ∥u∥2=∑ipi0=1\lVert u \rVert^2 = \sum_i p^0_i = 1, the matrix P=I−uu⊤P = I - u u^\top is the orthogonal projection onto the hyperplane u⊥u^\perp, of rank k−1k - 1. Choose an orthonormal basis q1,…,qk−1q_1, \ldots, q_{k - 1} of u⊥u^\perp and let Z∼N(0,Ik)Z \sim N(0, I_k). The vector PZPZ is normal with covariance PP⊤=PP P^\top = P, so it has the law of WW. Also PZ=∑j<k(qj⊤Z)qjPZ = \sum_{j < k} (q_j^\top Z) q_j, so ∥PZ∥2=∑j=1k−1(qj⊤Z)2\lVert PZ \rVert^2 = \sum_{j = 1}^{k - 1} (q_j^\top Z)^2. The qj⊤Zq_j^\top Z are jointly normal with covariance qj⊤ql=[j=l]q_j^\top q_l = [j = l], so they are iid standard normal, and ∥W∥2\lVert W \rVert^2 has the χk−12\chi^2_{k - 1} law. □\square

Claim 4 (the size tends to the nominal level). For a fixed α∈(0,1)\alpha \in (0, 1), the test that rejects when p≤αp \le \alpha has PH0(reject)→αP_{H_0}(\text{reject}) \to \alpha.

Proof. Rejecting when P(χk−12>X2)≤αP(\chi^2_{k-1} > X^2) \le \alpha is rejecting when X2≥cX^2 \ge c, where cc is the upper α\alpha point of χk−12\chi^2_{k - 1}, because the tail function is continuous and strictly decreasing. The limit law is continuous, so P(X2≥c)→P(χk−12≥c)=αP(X^2 \ge c) \to P(\chi^2_{k - 1} \ge c) = \alpha. □\square

The convergence is not uniform in p0p^0. If some npi0n p^0_i is small, the multinomial law is far from its normal limit, and the true size can be above or below α\alpha. The tests compute the exact size by summing the multinomial probabilities of all outcomes for several small cases.

Claim 5 (two categories). For k=2k = 2, X2=z2X^2 = z^2 with z=(O1−np10)/np10(1−p10)z = (O_1 - n p^0_1)/\sqrt{n p^0_1 (1 - p^0_1)}, the score statistic of the binomial test.

Proof. Let d=O1−np10d = O_1 - n p^0_1. Then O2−np20=−dO_2 - n p^0_2 = -d, so X2=d2(1/(np10)+1/(np20))=d2/(np10p20)X^2 = d^2 \big(1/(n p^0_1) + 1/(n p^0_2)\big) = d^2/(n p^0_1 p^0_2), which is z2z^2. □\square

Claim 6 (the G statistic has the same limit). Under H0H_0, G−X2→0G - X^2 \to 0 in probability, so GG also tends to χk−12\chi^2_{k - 1}.

Proof. Let f(t)=2(1+t)log⁡(1+t)−2t−t2f(t) = 2(1 + t)\log(1 + t) - 2t - t^2 for t>−1t > -1. Then f(0)=f′(0)=f′′(0)=0f(0) = f'(0) = f''(0) = 0 and f′′′(t)=−2/(1+t)2f'''(t) = -2/(1 + t)^2, so ∣f′′′(t)∣≤8\lvert f'''(t) \rvert \le 8 for t≥−1/2t \ge -1/2, and Taylor's theorem gives ∣f(t)∣≤43∣t∣3\lvert f(t) \rvert \le \tfrac43 \lvert t \rvert^3 there. Put di=Oi−Eid_i = O_i - E_i and ti=di/Eit_i = d_i/E_i. Then Oi=Ei(1+ti)O_i = E_i(1 + t_i) and 2Oilog⁡(Oi/Ei)=Ei(2ti+ti2+f(ti))2 O_i \log(O_i/E_i) = E_i(2t_i + t_i^2 + f(t_i)) when Oi>0O_i > 0. Summing over ii and using ∑idi=0\sum_i d_i = 0,

G=∑idi2Ei+∑iEif(ti)=X2+∑iEif(ti).G = \sum_i \frac{d_i^2}{E_i} + \sum_i E_i f(t_i) = X^2 + \sum_i E_i f(t_i).

By Claim 3, each di/nd_i/\sqrt n is bounded in probability, so ti=OP(n−1/2)t_i = O_P(n^{-1/2}). On the event that all ∣ti∣≤1/2\lvert t_i \rvert \le 1/2 (all Oi>0O_i > 0 then), whose probability tends to 1, ∣G−X2∣≤43∑i∣di∣3/Ei2=OP(n3/2/n2)=OP(n−1/2)\lvert G - X^2 \rvert \le \tfrac43 \sum_i \lvert d_i \rvert^3/E_i^2 = O_P(n^{3/2}/n^2) = O_P(n^{-1/2}). Slutsky's theorem gives the limit of GG. □\square

Fitted parameters (cited, not proved here). Suppose the null is a family p(θ)p(\theta) with θ∈Rs\theta \in \mathbb{R}^s, and θ^\hat\theta is the maximum likelihood estimate from the grouped counts OO (or the minimum chi-square estimate). Under smoothness and rank conditions, X2X^2 with Ei=npi(θ^)E_i = n p_i(\hat\theta) tends to χk−1−s2\chi^2_{k - 1 - s}. Fisher (1922, 1924) gave the result, and Cramér's 1946 book has a complete proof. The idea is the same as in Claim 3: the estimate removes ss more dimensions, and YnY_n tends to a normal vector on a subspace of dimension k−1−sk - 1 - s. If instead θ^\hat\theta is the maximum likelihood estimate from the ungrouped observations, Chernoff and Lehmann (1954) showed that the limit is ∑j≤k−1−sZj2+∑j=1sλjZk−1−s+j2\sum_{j \le k - 1 - s} Z_j^2 + \sum_{j = 1}^{s} \lambda_j Z_{k - 1 - s + j}^2 with iid standard normal ZjZ_j and λj∈[0,1]\lambda_j \in [0, 1], so it lies between χk−1−s2\chi^2_{k - 1 - s} and χk−12\chi^2_{k - 1}. The tests check this by simulation.

Cost. Lines L1 to L4 do Θ(k)\Theta(k) arithmetic operations and store the kk expected counts. Line L5 is one evaluation of the incomplete gamma function, which we count as one operation of the real-RAM model.

Complexity

The statistic takes Θ(k)\Theta(k) arithmetic operations, and the expected counts take Θ(k)\Theta(k) extra space (the code builds a list of them; a streaming version needs Θ(1)\Theta(1)). The p-value is one evaluation of the incomplete gamma function. Counting the observations into categories, if the caller has raw data, is a separate Θ(n)\Theta(n) pass.

Properties

  • Size for small samples (computed exactly). Under the null the outcome is a finite multinomial, so the true size of the test at α=0.05\alpha = 0.05 can be found by summing over all outcomes. The tests do this and also check it against a simulation.

    nn p0p^0 smallest EiE_i size of X2X^2 test size of GG test
    10 (1/3,1/3,1/3)(1/3, 1/3, 1/3) 3.33 0.0590 0.0565
    30 (1/3,1/3,1/3)(1/3, 1/3, 1/3) 10 0.0478 0.0597
    20 (1/4,1/4,1/4,1/4)(1/4, 1/4, 1/4, 1/4) 5 0.0415 0.0528
    20 (0.7,0.1,0.1,0.1)(0.7, 0.1, 0.1, 0.1) 2 0.0491 0.0624
    50 (0.7,0.1,0.1,0.1)(0.7, 0.1, 0.1, 0.1) 5 0.0513 0.0567

    The Pearson statistic stays close to 0.05 even with expected counts of 2. The GG statistic is more liberal in these cases.

  • Fitted parameters lower the degrees of freedom. Each parameter fitted by maximum likelihood from the grouped counts removes one degree of freedom.

  • Estimates from raw data. The Chernoff-Lehmann limit lies between the two chi-square laws. In a simulation (seed 5, 4000 samples of n=100n = 100 standard normal values, six fixed bins, mean and standard deviation estimated from the raw values), the test with 6−1−2=36 - 1 - 2 = 3 degrees of freedom rejected 5.5% of the time, and the test with 5 degrees of freedom rejected 1.1% of the time. The theory says the first is slightly liberal, and the simulation agrees within its standard error of 0.35%. The second is very conservative.

  • Power. For the die with n=60n = 60 and a loaded face 6 (p6=1/3p_6 = 1/3, the others 2/152/15), the power at α=0.05\alpha = 0.05 was 0.698 for X2X^2 and 0.663 for GG in a simulation (seed 9, 20000 samples). The noncentral chi-square approximation with λ=12\lambda = 12 gives 0.769, which is too high at this sample size.

  • Invariant to the order of the categories. The statistic ignores any order. This is a weakness when the categories are ordered.

Variants and improvements

  • Likelihood-ratio statistic GG. The code computes it with statistic="g". It has the same limit, and it adds up over nested models, which X2X^2 does not do exactly.
  • Power-divergence family. Cressie and Read (1984) put X2X^2 and GG in one family indexed by λ\lambda, with X2X^2 at λ=1\lambda = 1 and GG at λ=0\lambda = 0. They recommend λ=2/3\lambda = 2/3.
  • Exact multinomial test. For small nn, sum the multinomial probabilities of all outcomes at least as unlikely as the observed one, or as large in X2X^2, by enumeration as in the tests. For k=2k = 2 this is the binomial test.
  • Monte Carlo p-value. Simulate multinomial samples under p0p^0 and use (1+count)/(1+B)(1 + \text{count})/(1 + B), where the count is the number of simulated X2X^2 values at least the observed one.
  • Continuous data. For a fully specified continuous distribution, tests based on the empirical distribution function, such as the Kolmogorov-Smirnov and Anderson-Darling tests, do not need bins and usually have more power.

When to use it

Use it for counts in categories that have no order, with a null hypothesis that gives the category probabilities or a model with a few parameters. Typical uses are genetic ratios, checks of a random number generator, and checks of a discrete model. A common rule asks for all expected counts of at least 5. The table above shows that the Pearson test holds its size well with expected counts near 2, so Cochran's rule (no expected count below 1, and at most 20% below 5) is a better guide. For smaller counts, use the exact or Monte Carlo test.

Pitfalls

  • Percentages instead of counts. The statistic must use counts. Using percentages changes nn to 100 and gives a wrong p-value.
  • Observations that are not independent. Repeated measurements on the same people, or clustered data, make the variance larger than the multinomial variance, and the test rejects too often.
  • Wrong degrees of freedom. Subtract one degree of freedom for each parameter fitted from the counts. If the parameters came from the raw data, k−1−sk - 1 - s degrees of freedom make the test slightly liberal and k−1k - 1 make it conservative.
  • Choosing bins after seeing the data. Choosing bins to make the fit look good or bad changes the null law.
  • Reading a large p-value as proof of the model. A large p-value means only that the test did not detect a misfit. With small nn the power is low. A p-value very close to 1 can also be a warning: Fisher (1936) argued that the totals of Mendel's experiments agreed with theory too well.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

chi_squared_gof.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chi-squared-goodness-of-fit-test/. The authors are listed in prov/B43M8J.jsonl.

import math
from collections.abc import Sequence

from stdist import chi2_sf


def chi_squared_gof(
    observed: Sequence[int],
    probs: Sequence[float] | None = None,
    fitted: int = 0,
    statistic: str = "pearson",
) -> tuple[float, int, float]:
    """Pearson's chi-squared goodness-of-fit test.

    observed holds the counts of k categories; probs holds the null cell
    probabilities (equal cells when None). fitted is the number s of
    parameters estimated by maximum likelihood from these grouped counts,
    which lowers the degrees of freedom to k - 1 - s. statistic "pearson"
    gives X^2 = sum (O - E)^2 / E; "g" gives the likelihood-ratio statistic
    G = 2 sum O log(O / E). Returns (statistic, degrees of freedom, p-value),
    where the p-value is the upper tail of the chi-square law.
    """
    k = len(observed)
    if k < 2 or any(not isinstance(o, int) or o < 0 for o in observed):
        raise ValueError("need at least two non-negative integer counts")
    if probs is None:
        probs = [1.0 / k] * k
    if len(probs) != k or any(not p > 0 for p in probs) or abs(math.fsum(probs) - 1.0) > 1e-9:
        raise ValueError("probs must be k positive numbers that sum to 1")
    if statistic not in ("pearson", "g"):
        raise ValueError("unknown statistic")
    n = sum(observed)  # @line L1
    if n == 0:
        raise ValueError("need at least one observation")
    expected = [n * p for p in probs]  # @line L2
    if statistic == "pearson":  # @line L3
        x2 = math.fsum((o - e) ** 2 / e for o, e in zip(observed, expected))
    else:
        x2 = 2.0 * math.fsum(o * math.log(o / e) for o, e in zip(observed, expected) if o > 0)
    df = k - 1 - fitted  # @line L4
    if df < 1:
        raise ValueError("need k - 1 - fitted >= 1")
    return x2, df, chi2_sf(x2, df)  # @line L5
stdist.py 238 lines
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Normal, chi-square, t and F distribution functions in the standard library.

The incomplete gamma and beta functions return a lower tail and an upper
tail, and each tail is computed directly where it is small, so an upper tail
such as chi2_sf(200, 3) does not come from 1 - cdf and does not cancel.
Quantiles use a safeguarded bisection on the CDF (lower half) or on the upper
tail (upper half); the bracket shrinks until floating point stops it, so the
probability error is that of the CDF, below 1e-12 for moderate parameters.
"""

import math
from statistics import NormalDist

_STD = NormalDist()
_EPS = 1e-16
_TINY = 1e-300
_MAXIT = 10000


def norm_cdf(x: float) -> float:
    """P(Z <= x) for a standard normal Z."""
    return 0.5 * math.erfc(-x / math.sqrt(2.0))


def norm_sf(x: float) -> float:
    """P(Z > x), computed with erfc, so it is accurate for large x."""
    return 0.5 * math.erfc(x / math.sqrt(2.0))


def norm_ppf(p: float) -> float:
    """The lower p-quantile z_p of the standard normal, 0 < p < 1."""
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    return _STD.inv_cdf(p)


def _gamma_tails(a: float, x: float) -> tuple[float, float]:
    """(P(a, x), Q(a, x)), the regularized lower and upper incomplete gamma."""
    if a <= 0.0 or x < 0.0:
        raise ValueError("need a > 0 and x >= 0")
    if x == 0.0:
        return 0.0, 1.0
    if math.isinf(x):
        return 1.0, 0.0
    front = math.exp(-x + a * math.log(x) - math.lgamma(a))
    if x < a + 1.0:
        # Series: P = front * sum_{j >= 0} x^j / (a (a + 1) ... (a + j)).
        ap, term = a, 1.0 / a
        total = term
        for _ in range(_MAXIT):
            ap += 1.0
            term *= x / ap
            total += term
            if abs(term) < abs(total) * _EPS:
                break
        p = front * total
        return p, 1.0 - p
    # Continued fraction for Q, modified Lentz.
    b = x + 1.0 - a
    c = 1.0 / _TINY
    d = 1.0 / b
    h = d
    for i in range(1, _MAXIT):
        an = -i * (i - a)
        b += 2.0
        d = an * d + b
        if abs(d) < _TINY:
            d = _TINY
        c = b + an / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        step = d * c
        h *= step
        if abs(step - 1.0) < _EPS:
            break
    q = front * h
    return 1.0 - q, q


def gamma_p(a: float, x: float) -> float:
    """Regularized lower incomplete gamma P(a, x)."""
    return _gamma_tails(a, x)[0]


def gamma_q(a: float, x: float) -> float:
    """Regularized upper incomplete gamma Q(a, x) = 1 - P(a, x)."""
    return _gamma_tails(a, x)[1]


def _beta_cf(a: float, b: float, x: float) -> float:
    """The continued fraction of I_x(a, b), modified Lentz."""
    qab, qap, qam = a + b, a + 1.0, a - 1.0
    c = 1.0
    d = 1.0 - qab * x / qap
    if abs(d) < _TINY:
        d = _TINY
    d = 1.0 / d
    h = d
    for m in range(1, _MAXIT):
        m2 = 2 * m
        aa = m * (b - m) * x / ((qam + m2) * (a + m2))
        d = 1.0 + aa * d
        if abs(d) < _TINY:
            d = _TINY
        c = 1.0 + aa / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        h *= d * c
        aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
        d = 1.0 + aa * d
        if abs(d) < _TINY:
            d = _TINY
        c = 1.0 + aa / c
        if abs(c) < _TINY:
            c = _TINY
        d = 1.0 / d
        step = d * c
        h *= step
        if abs(step - 1.0) < _EPS:
            break
    return h


def _beta_tails(a: float, b: float, x: float, y: float | None = None) -> tuple[float, float]:
    """(I_x(a, b), 1 - I_x(a, b)), each computed directly where it is small.

    y is 1 - x; pass it when it is known more accurately than 1 - x.
    """
    if a <= 0.0 or b <= 0.0:
        raise ValueError("need a > 0 and b > 0")
    if y is None:
        y = 1.0 - x
    if x <= 0.0:
        return 0.0, 1.0
    if y <= 0.0:
        return 1.0, 0.0
    front = math.exp(
        math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
        + a * math.log(x) + b * math.log(y)
    )
    if x < (a + 1.0) / (a + b + 2.0):
        low = front * _beta_cf(a, b, x) / a
        return low, 1.0 - low
    # Symmetry: I_x(a, b) = 1 - I_(1-x)(b, a).
    up = front * _beta_cf(b, a, y) / b
    return 1.0 - up, up


def beta_inc(a: float, b: float, x: float) -> float:
    """Regularized incomplete beta function I_x(a, b)."""
    return _beta_tails(a, b, x)[0]


def chi2_cdf(x: float, k: float) -> float:
    """P(X <= x) for X chi-square with k > 0 degrees of freedom."""
    return 0.0 if x <= 0.0 else gamma_p(k / 2.0, x / 2.0)


def chi2_sf(x: float, k: float) -> float:
    """P(X > x) for X chi-square with k degrees of freedom, without 1 - cdf."""
    return 1.0 if x <= 0.0 else gamma_q(k / 2.0, x / 2.0)


def t_sf(x: float, k: float) -> float:
    """P(T > x) for T Student t with k > 0 degrees of freedom."""
    if math.isfinite(x):
        s = k + x * x
        half = 0.5 * _beta_tails(k / 2.0, 0.5, k / s, x * x / s)[0]  # P(|T| > |x|) / 2
    else:
        half = 0.0
    return half if x >= 0.0 else 1.0 - half


def t_cdf(x: float, k: float) -> float:
    """P(T <= x) for T Student t with k degrees of freedom."""
    return t_sf(-x, k)


def f_cdf(x: float, k1: float, k2: float) -> float:
    """P(F <= x) for F with (k1, k2) degrees of freedom."""
    if x <= 0.0:
        return 0.0
    return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[1]


def f_sf(x: float, k1: float, k2: float) -> float:
    """P(F > x) = I_(k2 / (k2 + k1 x))(k2 / 2, k1 / 2)."""
    if x <= 0.0:
        return 1.0
    return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[0]


def _quantile(cdf, sf, p: float, lo: float, hi: float) -> float:
    """The x with cdf(x) = p, by bisection on cdf (p <= 1/2) or on sf (p > 1/2).

    lo must satisfy cdf(lo) <= p; hi is doubled until cdf(hi) >= p.
    """
    if not 0.0 < p < 1.0:
        raise ValueError("p must be in (0, 1)")
    if p <= 0.5:
        g = lambda x: cdf(x) - p  # increasing in x
    else:
        q = 1.0 - p
        g = lambda x: q - sf(x)  # increasing in x, and no cancellation in sf
    while g(hi) < 0.0:
        lo, hi = hi, 2.0 * hi if hi > 0.0 else 1.0
    for _ in range(400):
        mid = 0.5 * (lo + hi)
        if mid <= lo or mid >= hi:
            break
        if g(mid) < 0.0:
            lo = mid
        else:
            hi = mid
    return 0.5 * (lo + hi)


def chi2_ppf(p: float, k: float) -> float:
    """The lower p-quantile chi^2_(k, p)."""
    return _quantile(lambda x: chi2_cdf(x, k), lambda x: chi2_sf(x, k), p, 0.0, max(1.0, k))


def t_ppf(p: float, k: float) -> float:
    """The lower p-quantile t_(k, p)."""
    if p == 0.5:
        return 0.0
    if p < 0.5:
        return -t_ppf(1.0 - p, k)
    return _quantile(lambda x: t_cdf(x, k), lambda x: t_sf(x, k), p, 0.0, 1.0)


def f_ppf(p: float, k1: float, k2: float) -> float:
    """The lower p-quantile F_(k1, k2, p)."""
    return _quantile(lambda x: f_cdf(x, k1, k2), lambda x: f_sf(x, k1, k2), p, 0.0, 1.0)
chi_squared_goodness_of_fit_test.py 9 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chi-squared-goodness-of-fit-test/. The authors are listed in prov/B43M8J.jsonl.

"""Entry point named after the slug. The code lives in chi_squared_gof.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""

from chi_squared_gof import chi_squared_gof

__all__ = ["chi_squared_gof"]
test_chi_squared_goodness_of_fit_test.py 166 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chi-squared-goodness-of-fit-test/. The authors are listed in prov/B43M8J.jsonl.

import math
import random
from fractions import Fraction
from statistics import NormalDist

import pytest

from chi_squared_goodness_of_fit_test import chi_squared_gof
from stdist import chi2_sf

MENDEL = [315, 108, 101, 32]
MENDEL_P = [9 / 16, 3 / 16, 3 / 16, 1 / 16]


def exact_pearson(observed: list[int], probs: list[Fraction]) -> Fraction:
    n = sum(observed)
    return sum((Fraction(o) - n * p) ** 2 / (n * p) for o, p in zip(observed, probs))


def compositions(n: int, k: int):
    if k == 1:
        yield (n,)
        return
    for first in range(n + 1):
        for rest in compositions(n - first, k - 1):
            yield (first, *rest)


def multinomial_pmf(counts: tuple[int, ...], probs: list[float]) -> float:
    coef = math.factorial(sum(counts))
    for c in counts:
        coef //= math.factorial(c)
    return coef * math.prod(p**c for p, c in zip(probs, counts))


def test_page_examples() -> None:
    x2, df, p = chi_squared_gof([5, 8, 9, 8, 10, 20])
    assert (df, x2) == (5, pytest.approx(13.4))
    assert p == pytest.approx(0.019905, abs=1e-6)
    x2, df, p = chi_squared_gof(MENDEL, MENDEL_P)
    assert (df, x2, p) == (3, pytest.approx(0.470024, abs=1e-6), pytest.approx(0.925426, abs=1e-6))
    g2, df, p = chi_squared_gof(MENDEL, MENDEL_P, statistic="g")
    assert (df, g2, p) == (3, pytest.approx(0.475445, abs=1e-6), pytest.approx(0.924252, abs=1e-6))


def test_statistic_against_fractions() -> None:
    assert exact_pearson([5, 8, 9, 8, 10, 20], [Fraction(1, 6)] * 6) == Fraction(67, 5)
    assert exact_pearson(MENDEL, [Fraction(9, 16), Fraction(3, 16), Fraction(3, 16), Fraction(1, 16)]) == Fraction(
        19600, 41700
    )
    rng = random.Random(7)
    for _ in range(300):
        k = rng.randint(2, 7)
        weights = [rng.randint(1, 9) for _ in range(k)]
        probs = [Fraction(w, sum(weights)) for w in weights]
        observed = [rng.randint(0, 40) for _ in range(k)]
        if sum(observed) == 0:
            continue
        x2, df, _ = chi_squared_gof(observed, [float(p) for p in probs])
        assert df == k - 1
        assert x2 == pytest.approx(float(exact_pearson(observed, probs)), rel=1e-12, abs=1e-12)


def test_two_cells_is_the_squared_z_statistic() -> None:
    # With k = 2, X^2 = (x - n p)^2 / (n p (1 - p)) = z^2, and the 1 df tail is erfc(|z| / sqrt 2).
    for x, n, p0 in ((60, 100, 0.5), (3, 40, 0.2), (17, 20, 0.6), (0, 9, 0.3)):
        z = (x - n * p0) / math.sqrt(n * p0 * (1 - p0))
        x2, df, p = chi_squared_gof([x, n - x], [p0, 1 - p0])
        assert df == 1
        assert x2 == pytest.approx(z * z, rel=1e-12)
        assert p == pytest.approx(math.erfc(abs(z) / math.sqrt(2)), rel=1e-9)


def test_g_statistic_close_to_pearson_for_large_counts() -> None:
    # G - X^2 tends to 0 under the null; for counts near their expected values the two agree closely.
    for scale in (10, 100, 1000):
        obs = [9 * scale + 1, 3 * scale - 1, 3 * scale + 1, scale - 1]
        x2 = chi_squared_gof(obs, MENDEL_P)[0]
        g2 = chi_squared_gof(obs, MENDEL_P, statistic="g")[0]
        assert abs(g2 - x2) < 0.6 / scale


def exact_size(n: int, probs: list[float], alpha: float = 0.05) -> float:
    return math.fsum(
        multinomial_pmf(c, probs) for c in compositions(n, len(probs)) if chi_squared_gof(list(c), probs)[2] <= alpha
    )


def test_exact_size_by_enumeration() -> None:
    # The null law is a finite multinomial, so the true size of the asymptotic test can be computed exactly.
    assert exact_size(10, [1 / 3] * 3) == pytest.approx(0.058985, abs=1e-6)
    assert exact_size(30, [1 / 3] * 3) == pytest.approx(0.047786, abs=1e-6)
    assert exact_size(20, [0.25] * 4) == pytest.approx(0.041518, abs=1e-6)
    assert exact_size(20, [0.7, 0.1, 0.1, 0.1]) == pytest.approx(0.049088, abs=1e-6)
    assert exact_size(50, [0.7, 0.1, 0.1, 0.1]) == pytest.approx(0.051288, abs=1e-6)


def test_enumeration_against_brute_force_sampling() -> None:
    # Brute force: draw multinomial samples cell by cell and count rejections.
    rng = random.Random(11)
    probs = [1 / 3] * 3
    runs, rejected = 20000, 0
    for _ in range(runs):
        counts = [0, 0, 0]
        for _ in range(10):
            counts[rng.choices(range(3), probs)[0]] += 1
        rejected += chi_squared_gof(counts, probs)[2] <= 0.05
    size = exact_size(10, probs)
    assert abs(rejected / runs - size) < 4 * math.sqrt(size * (1 - size) / runs)


def test_fitted_parameter_hardy_weinberg() -> None:
    obs = [298, 489, 213]
    n = sum(obs)
    theta = (2 * obs[0] + obs[1]) / (2 * n)
    assert theta == 0.5425
    probs = [theta * theta, 2 * theta * (1 - theta), (1 - theta) ** 2]
    x2, df, p = chi_squared_gof(obs, probs, fitted=1)
    assert df == 1
    assert x2 == pytest.approx(0.221490, abs=1e-6)
    assert p == pytest.approx(0.637907, abs=1e-6)
    assert chi_squared_gof(obs, probs)[2] == pytest.approx(0.895167, abs=1e-6)


def test_chernoff_lehmann_raw_data_estimates() -> None:
    # Mean and standard deviation estimated from the raw normal data, six fixed bins.
    # The true law lies between chi2 with k - 1 - s = 3 and k - 1 = 5 degrees of freedom.
    rng = random.Random(5)
    cuts = [-1.5, -0.75, 0.0, 0.75, 1.5]
    std = NormalDist()
    runs, rej3, rej5 = 4000, 0, 0
    for _ in range(runs):
        x = [rng.gauss(0, 1) for _ in range(100)]
        m = math.fsum(x) / len(x)
        s = math.sqrt(math.fsum((v - m) ** 2 for v in x) / len(x))
        counts = [0] * 6
        for v in x:
            counts[sum(v > c for c in cuts)] += 1
        cdf = [0.0] + [std.cdf((c - m) / s) for c in cuts] + [1.0]
        probs = [cdf[i + 1] - cdf[i] for i in range(6)]
        x2, _, p = chi_squared_gof(counts, probs, fitted=2)
        rej3 += p <= 0.05
        rej5 += chi2_sf(x2, 5) <= 0.05
    assert rej3 / runs == pytest.approx(0.055, abs=1e-12)
    assert rej5 / runs == pytest.approx(0.01125, abs=1e-12)
    assert rej5 < 0.05 * runs


def test_errors() -> None:
    with pytest.raises(ValueError):
        chi_squared_gof([5])
    with pytest.raises(ValueError):
        chi_squared_gof([1, -1])
    with pytest.raises(ValueError):
        chi_squared_gof([1, 2], [0.5, 0.6])
    with pytest.raises(ValueError):
        chi_squared_gof([1, 2], [1.0, 0.0])
    with pytest.raises(ValueError):
        chi_squared_gof([0, 0])
    with pytest.raises(ValueError):
        chi_squared_gof([1, 2, 3], fitted=2)
    with pytest.raises(ValueError):
        chi_squared_gof([1, 2], statistic="z")

History

Karl Pearson published the statistic in 1900 as a criterion for deciding whether a set of deviations could come from random sampling, and gave its chi-square reference law with k−1k - 1 degrees of freedom. For tables with estimated margins and for fitted parameters, Pearson kept k−1k - 1. Fisher showed in 1922 and 1924 that each parameter fitted efficiently from the counts removes one degree of freedom. This was a long argument with Pearson. Cramér's 1946 book gave a complete proof of the limit. Chernoff and Lehmann (1954) showed that estimates from the ungrouped data give a limit that is not chi-square. Cochran (1952, 1954) studied small expected counts and gave the rules that are still in use. Cressie and Read (1984) put the Pearson and likelihood-ratio statistics into one family.

References

  1. Karl Pearson, On the criterion that a given system of deviations from the probable in the case of a correlated system of variables is such that it can be reasonably supposed to have arisen from random sampling, Philosophical Magazine, series 5, 50(302), 1900, pp. 157 to 175 (the statistic and its chi-square reference)
  2. Ronald A. Fisher, On the interpretation of χ² from contingency tables, and the calculation of P, Journal of the Royal Statistical Society 85(1), 1922, pp. 87 to 94 (the degrees of freedom when parameters are estimated)
  3. Herman Chernoff and Erich L. Lehmann, The use of maximum likelihood estimates in χ² tests for goodness of fit, Annals of Mathematical Statistics 25(3), 1954, pp. 579 to 586 (the limit law with estimates from ungrouped data)
  4. Alan Agresti, Categorical Data Analysis, third edition, Wiley, 2013, Chapter 1 (inference for multinomial parameters, the Pearson and likelihood-ratio statistics)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example