Algorithm Search⌘K

Algorithmintro

Z-test

Also called normal test, one-sample z-test.

Tests a mean or proportion with a statistic that is standard normal under the null. Exact for normal data with known sigma, asymptotic for proportions. O(n) time.

Time
Θ(n) worst · best
Space
Θ(1) extra
Where
n = the number of observations
Properties
deterministicexactonlineiterative
Origin
Ronald A. Fisher, 1925

The z-test is a statistical hypothesis test whose statistic is a difference between an estimate and its null value, divided by a known standard error, so that the statistic is standard normal under the null hypothesis. For iid normal data with a known standard deviation σ\sigma, the null distribution is exactly N(0,1)N(0, 1) for every sample size, and the test has size exactly α\alpha. For a proportion, and for any mean when σ\sigma is replaced by a large-sample value, the normal law holds only in the limit, by the central limit theorem, and the size is only near α\alpha. The computation is one pass over the data and one evaluation of the normal tail.

In plain words

You know how much single measurements scatter. You want to know if their true average is some claimed value. Take the average of your measurements, subtract the claimed value, and divide by the typical scatter of an average of that many measurements. The result counts how many "typical errors" the average is away from the claim. If the claim is right, this count behaves like a draw from the bell curve, so you know how often it lands far from zero by chance. A count of about two or more is rare: it happens about one time in twenty. When it happens, you reject the claim. The same idea tests a share of yes answers, but there the bell curve is only an approximation that improves as the sample grows.

The problem

One-sample test of a mean. The data are X1,…,XnX_1, \dots, X_n iid N(μ,σ2)N(\mu, \sigma^2), with σ>0\sigma > 0 known and μ\mu unknown. The null hypothesis is H0:μ=μ0H_0: \mu = \mu_0. The alternative is two-sided, H1:μ≠μ0H_1: \mu \ne \mu_0, or one-sided, H1:μ>μ0H_1: \mu > \mu_0 ("greater") or H1:μ<μ0H_1: \mu < \mu_0 ("less"). For a one-sided alternative the null can also be the composite μ≤μ0\mu \le \mu_0 (or μ≥μ0\mu \ge \mu_0), with the same test.

Statistic. With the sample mean Xˉ=1n∑Xi\bar X = \frac1n\sum X_i,

Z=Xˉ−μ0σ/n.Z = \frac{\bar X - \mu_0}{\sigma/\sqrt n}.

Null distribution. Exact: Z∼N(0,1)Z \sim N(0, 1) under H0H_0 for every n≥1n \ge 1. In general Z∼N(λ,1)Z \sim N(\lambda, 1) with λ=n(μ−μ0)/σ\lambda = \sqrt n(\mu - \mu_0)/\sigma.

Rejection rule and size. At level α\alpha, with the lower quantiles zpz_p of N(0,1)N(0, 1): reject when ∣Z∣≥z1−α/2|Z| \ge z_{1-\alpha/2} (two-sided), Z≥z1−αZ \ge z_{1-\alpha} ("greater") or Z≤zαZ \le z_\alpha ("less"). The size equals α\alpha exactly. For α=0.05\alpha = 0.05, z0.975≈1.959964z_{0.975} \approx 1.959964 and z0.95≈1.644854z_{0.95} \approx 1.644854.

p-value. With the observed value zz and Φˉ(z)=1−Φ(z)\bar\Phi(z) = 1 - \Phi(z) the upper tail: p=Φˉ(z)p = \bar\Phi(z) ("greater"), p=Φ(z)p = \Phi(z) ("less"), and p=2Φˉ(∣z∣)p = 2\bar\Phi(|z|) (two-sided). The null law is symmetric, so doubling the smaller tail and summing the outcomes no more likely than the observed one give the same two-sided p-value.

Sensitivity and power. The test reacts to a shift of the mean. Its power at μ\mu is, for the two-sided test,

π(μ)=Φ(λ−z1−α/2)+Φ(−λ−z1−α/2),λ=n(μ−μ0)σ,\pi(\mu) = \Phi(\lambda - z_{1-\alpha/2}) + \Phi(-\lambda - z_{1-\alpha/2}), \qquad \lambda = \frac{\sqrt n(\mu - \mu_0)}{\sigma},

and Φ(λ−z1−α)\Phi(\lambda - z_{1-\alpha}) for "greater". The one-sided test is uniformly most powerful for its alternative (by the Neyman-Pearson lemma and the Karlin-Rubin theorem), and the two-sided test is uniformly most powerful among unbiased tests (Lehmann and Romano, Chapters 3 and 4).

Two other forms. The two-sample test compares independent normal samples of sizes mm and nn with known σX\sigma_X and σY\sigma_Y, with H0:μX−μY=δ0H_0: \mu_X - \mu_Y = \delta_0 and Z=(Xˉ−Yˉ−δ0)/σX2/m+σY2/nZ = (\bar X - \bar Y - \delta_0)/\sqrt{\sigma_X^2/m + \sigma_Y^2/n}; it is exact. The one-proportion test takes KK successes in nn Bernoulli trials (binomial distribution), H0:p=p0H_0: p = p_0, and Z=(K−np0)/np0(1−p0)Z = (K - np_0)/\sqrt{np_0(1 - p_0)}, with the standard error computed at p0p_0. Its null distribution is N(0,1)N(0, 1) only asymptotically, so its size is only near α\alpha.

The algorithm

  1. Z-TEST(x[1..n], μ₀, σ, alternative) ▷ σ > 0 known, n ≥ 1
  2. 1n ← the length of x
  3. 2s ← x[1] + x[2] + ... + x[n] ▷ an accurate sum, see below
  4. 3x̄ ← s / n
  5. 4z ← (x̄ − μ₀) / (σ / √n)
  6. 5return (z, NORMAL-P-VALUE(z, alternative))
  7. NORMAL-P-VALUE(z, alternative)
  8. 6if alternative = two-sided then return min(1, 2 · Φ̄(|z|))
  9. 7if alternative = greater then return Φ̄(z)
  10. 8if alternative = less then return Φ(z)

Here Φˉ(z)=12erfc⁡(z/2)\bar\Phi(z) = \tfrac12\operatorname{erfc}(z/\sqrt2) and Φ(z)=12erfc⁡(−z/2)\Phi(z) = \tfrac12\operatorname{erfc}(-z/\sqrt2), where erfc is the complementary error function of the math library. The test rejects at level α\alpha when the returned p≤αp \le \alpha, which is the same as the quantile rules above. The two-sample and proportion forms change only lines L1 to L4: they compute their own zz and call NORMAL-P-VALUE.

Example

A filling machine is set to put 500 g in each pack, and the scatter of single packs is known from long experience: σ=4\sigma = 4 g. Nine packs weigh

502, 498, 505, 503, 501, 507, 499, 504, 506.502,\ 498,\ 505,\ 503,\ 501,\ 507,\ 499,\ 504,\ 506 .

Test H0:μ=500H_0: \mu = 500 against H1:μ≠500H_1: \mu \ne 500 at α=0.05\alpha = 0.05.

step value
L2: ss 45254525
L3: xˉ=4525/9\bar x = 4525/9 502.7778502.7778
L4: σ/n=4/3\sigma/\sqrt n = 4/3 1.33331.3333
L4: z=(25/9)/(4/3)=25/12z = (25/9)/(4/3) = 25/12 2.08332.0833
L6: p=2Φˉ(2.0833)p = 2\bar\Phi(2.0833) 0.0372210.037221

Since p=0.0372≤0.05p = 0.0372 \le 0.05 (equivalently 2.0833≥1.9599642.0833 \ge 1.959964), the test rejects H0H_0 at the 5% level. The one-sided p-value for H1:μ>500H_1: \mu > 500 is 0.0186100.018610, half of the two-sided one. The test does not reject at the 1% level, where the two-sided critical value is z0.995≈2.575829z_{0.995} \approx 2.575829.

The power of this design (n=9n = 9, σ=4\sigma = 4, two-sided, α=0.05\alpha = 0.05) at a few true means:

true μ\mu λ=3(μ−500)/4\lambda = 3(\mu - 500)/4 power π(μ)\pi(\mu)
500.5 0.375 0.0663
501 0.75 0.1165
502 1.5 0.3230
503 2.25 0.6141
504 3.0 0.8508
505 3.75 0.9633

A true overfill of 3 g is detected only 61% of the time with nine packs. Sample size determination turns this table around.

The proportion form shows what "only near α\alpha" means. With n=100n = 100 and p0=1/2p_0 = 1/2, Z=(K−50)/5Z = (K - 50)/5, and the two-sided test at α=0.05\alpha = 0.05 rejects exactly when ∣K−50∣≥10|K - 50| \ge 10. The exact size, a sum of binomial probabilities, is 0.0568880.056888, not 0.050.05. More exact sizes of the same nominal 5% test:

nn p0p_0 exact size
20 0.5 0.041389
50 0.5 0.064909
100 0.5 0.056888
1000 0.5 0.053678
30 0.1 0.025827
100 0.1 0.063602

The size moves above and below α\alpha because KK is discrete, and it is far from α\alpha when np0np_0 is small. The exact binomial test has size at most α\alpha for every nn.

Correctness

Under the normal model, Xˉ\bar X is a sum of independent normals divided by nn, so it is normal with mean μ\mu and variance σ2/n\sigma^2/n. Then ZZ is an affine function of a normal variable with mean λ\lambda and variance 1, which is N(0,1)N(0, 1) under H0H_0. Each p-value of lines L6 to L8 is the probability under H0H_0 of a statistic at least as extreme as zz, and since Φ\Phi is continuous and strictly increasing, PH0(p≤u)=uP_{H_0}(p \le u) = u for each uu, so the size is exactly α\alpha. For the composite one-sided null μ≤μ0\mu \le \mu_0, the rejection probability increases in μ\mu, so its maximum over the null is at μ0\mu_0. The proportion statistic is a standardized sum of iid Bernoulli variables and converges in distribution to N(0,1)N(0, 1) by the central limit theorem, so its size tends to α\alpha. The proofs, with the power function and its monotonicity, are in the correctness proof below.

Proof: The z-test has exact size alpha under normal data with known sigma, and the proportion z-test has size tending to alphafull

We prove that the statistic of Z-TEST has the standard normal distribution under H0H_0, that the rejection rules have size exactly α\alpha, that the p-values are the stated tail probabilities and are uniform under H0H_0, and that the proportion version has size that tends to α\alpha. Φ\Phi is the standard normal CDF and zp=Φ−1(p)z_p = \Phi^{-1}(p) is its lower pp-quantile.

Lemma 1 (the null distribution). Let X1,…,XnX_1, \dots, X_n be iid N(μ,σ2)N(\mu, \sigma^2) with σ>0\sigma > 0 known. Then Z=n(Xˉ−μ0)/σZ = \sqrt n(\bar X - \mu_0)/\sigma has the distribution N(λ,1)N(\lambda, 1) with λ=n(μ−μ0)/σ\lambda = \sqrt n(\mu - \mu_0)/\sigma. In particular Z∼N(0,1)Z \sim N(0, 1) exactly when μ=μ0\mu = \mu_0, for every n≥1n \ge 1.

Proof. The moment generating function of XiX_i is M(s)=exp⁡(μs+σ2s2/2)M(s) = \exp(\mu s + \sigma^2 s^2/2). By independence, the moment generating function of ∑Xi\sum X_i is M(s)n=exp⁡(nμs+nσ2s2/2)M(s)^n = \exp(n\mu s + n\sigma^2 s^2/2), which is that of N(nμ,nσ2)N(n\mu, n\sigma^2). A moment generating function that is finite near 0 fixes the distribution, so ∑Xi∼N(nμ,nσ2)\sum X_i \sim N(n\mu, n\sigma^2). An affine map a+bYa + bY of a normal Y∼N(m,v)Y \sim N(m, v) is N(a+bm,b2v)N(a + bm, b^2 v), by the same argument. With b=1/(n σ)b = 1/(\sqrt n\,\sigma) and a=−n μ0/σa = -\sqrt n\,\mu_0/\sigma, Z=a+b∑XiZ = a + b\sum X_i has mean n(μ−μ0)/σ\sqrt n(\mu - \mu_0)/\sigma and variance nσ2/(nσ2)=1n\sigma^2/(n\sigma^2) = 1. □\square

Lemma 2 (the two-sample statistic). Let X1,…,XmX_1, \dots, X_m be iid N(μX,σX2)N(\mu_X, \sigma_X^2) and Y1,…,YnY_1, \dots, Y_n iid N(μY,σY2)N(\mu_Y, \sigma_Y^2), the two samples independent, with σX,σY\sigma_X, \sigma_Y known. Then Z=(Xˉ−Yˉ−δ0)/σX2/m+σY2/n∼N(0,1)Z = (\bar X - \bar Y - \delta_0)/\sqrt{\sigma_X^2/m + \sigma_Y^2/n} \sim N(0, 1) when μX−μY=δ0\mu_X - \mu_Y = \delta_0.

Proof. By Lemma 1, Xˉ∼N(μX,σX2/m)\bar X \sim N(\mu_X, \sigma_X^2/m) and Yˉ∼N(μY,σY2/n)\bar Y \sim N(\mu_Y, \sigma_Y^2/n), and they are independent. The product of their moment generating functions at ss and −s-s shows Xˉ−Yˉ∼N(μX−μY,σX2/m+σY2/n)\bar X - \bar Y \sim N(\mu_X - \mu_Y, \sigma_X^2/m + \sigma_Y^2/n). Standardize as in Lemma 1. □\square

Lemma 3 (p-values and size). Let Z∼N(0,1)Z \sim N(0, 1) under H0H_0, and let zz be the observed value. The p-values computed by NORMAL-P-VALUE are PH0(Z≥z)P_{H_0}(Z \ge z) for "greater", PH0(Z≤z)P_{H_0}(Z \le z) for "less" and PH0(∣Z∣≥∣z∣)P_{H_0}(|Z| \ge |z|) for "two-sided". For each, PH0(p≤u)=uP_{H_0}(p \le u) = u for every u∈[0,1]u \in [0, 1]. So the rule "reject when p≤αp \le \alpha" has size exactly α\alpha.

Proof. P(Z≥z)=1−Φ(z)=Φˉ(z)P(Z \ge z) = 1 - \Phi(z) = \bar\Phi(z), which the code computes as 12erfc⁡(z/2)\tfrac12\operatorname{erfc}(z/\sqrt2); this is the same function, since Φ(x)=12erfc⁡(−x/2)\Phi(x) = \tfrac12\operatorname{erfc}(-x/\sqrt2) and erfc⁡(−t)=2−erfc⁡(t)\operatorname{erfc}(-t) = 2 - \operatorname{erfc}(t). P(Z≤z)=Φ(z)P(Z \le z) = \Phi(z). By symmetry of the standard normal, P(∣Z∣≥∣z∣)=2Φˉ(∣z∣)P(|Z| \ge |z|) = 2\bar\Phi(|z|), which is at most 1 because Φˉ(∣z∣)≤1/2\bar\Phi(|z|) \le 1/2; the min with 1 only guards rounding. For uniformity, take "greater": p=Φˉ(Z)p = \bar\Phi(Z), and Φˉ\bar\Phi is continuous and strictly decreasing, so {p≤u}={Z≥Φˉ−1(u)}\{p \le u\} = \{Z \ge \bar\Phi^{-1}(u)\}, which has probability uu. For "two-sided", {p≤u}={∣Z∣≥z1−u/2}\{p \le u\} = \{|Z| \ge z_{1-u/2}\}, which has probability 2(1−(1−u/2))=u2(1 - (1 - u/2)) = u. "less" is the mirror image of "greater". □\square

So "reject when p≤αp \le \alpha" is the same as "reject when z≥z1−αz \ge z_{1-\alpha}" ("greater"), "z≤zαz \le z_\alpha" ("less") or "∣z∣≥z1−α/2|z| \ge z_{1-\alpha/2}" ("two-sided").

Lemma 4 (the one-sided test is valid on the composite null). For H0:μ≤μ0H_0: \mu \le \mu_0 against H1:μ>μ0H_1: \mu > \mu_0, the rule "reject when Z≥z1−αZ \ge z_{1-\alpha}" has size exactly α\alpha.

Proof. By Lemma 1, Pμ(Z≥z1−α)=1−Φ(z1−α−λ)P_\mu(Z \ge z_{1-\alpha}) = 1 - \Phi(z_{1-\alpha} - \lambda), which increases in λ\lambda and so in μ\mu. Its supremum over μ≤μ0\mu \le \mu_0 is its value at μ0\mu_0, which is α\alpha. □\square

Lemma 5 (the power function). The two-sided test at level α\alpha rejects with probability π(μ)=Φ(λ−z1−α/2)+Φ(−λ−z1−α/2)\pi(\mu) = \Phi(\lambda - z_{1-\alpha/2}) + \Phi(-\lambda - z_{1-\alpha/2}). It is even in λ\lambda, equals α\alpha at λ=0\lambda = 0, and increases in ∣λ∣|\lambda|, so the test is unbiased.

Proof. By Lemma 1, with c=z1−α/2c = z_{1-\alpha/2}, P(Z≥c)=Φ(λ−c)P(Z \ge c) = \Phi(\lambda - c) and P(Z≤−c)=Φ(−λ−c)P(Z \le -c) = \Phi(-\lambda - c). The sum is even in λ\lambda. Its derivative in λ\lambda is φ(λ−c)−φ(λ+c)\varphi(\lambda - c) - \varphi(\lambda + c), where φ\varphi is the standard normal density. For λ>0\lambda > 0 and c>0c > 0, ∣λ−c∣<λ+c|\lambda - c| < \lambda + c, so φ(λ−c)>φ(λ+c)\varphi(\lambda - c) > \varphi(\lambda + c) and the derivative is positive. □\square

Lemma 6 (the proportion test is asymptotic). Let K∼Binomial(n,p0)K \sim \text{Binomial}(n, p_0) with 0<p0<10 < p_0 < 1 fixed, and Zn=(K−np0)/np0(1−p0)Z_n = (K - np_0)/\sqrt{np_0(1 - p_0)}. Then ZnZ_n converges in distribution to N(0,1)N(0, 1), and the size of each rule of Lemma 3 tends to α\alpha as n→∞n \to \infty.

Proof. KK is a sum of nn iid Bernoulli(p0p_0) variables with mean p0p_0 and variance p0(1−p0)∈(0,∞)p_0(1 - p_0) \in (0, \infty), so the central limit theorem gives the convergence in distribution. The limit CDF Φ\Phi is continuous, so P(Zn≥c)→1−Φ(c)P(Z_n \ge c) \to 1 - \Phi(c) for each fixed cc, and the same for the lower and the two-sided rules. □\square

The convergence of Lemma 6 is not uniform in p0p_0: for fixed nn, the size can be far from α\alpha when np0np_0 is small. For each finite nn the size is a sum of binomial terms, which the tests compute exactly.

Termination. Z-TEST makes one pass over the nn observations and then a constant number of operations, so it stops after n+O(1)n + O(1) steps.

Theorem. Under the model of Lemma 1 (or Lemma 2), Z-TEST returns the statistic ZZ and the p-value PH0(a statistic at least as extreme as z)P_{H_0}(\text{a statistic at least as extreme as } z), and rejecting when p≤αp \le \alpha gives a test of size exactly α\alpha, for every n≥1n \ge 1. The proportion version has size that tends to α\alpha.

Proof. Lemmas 1 to 4 for the normal versions, and Lemma 6 for the proportion version. ■\blacksquare

Complexity

On a real RAM, lines L1 to L3 make nn additions and one division, line L4 a constant number of operations, and lines L6 to L8 one evaluation of erfc. So the time is Θ(n)\Theta(n) and the extra space is Θ(1)\Theta(1). The test is online: the running sum can take one observation at a time, and zz is available after each one. The proportion form needs only KK and nn, so it costs O(1)O(1) after counting.

Numerical stability. Two places lose accuracy if they are written carelessly.

  • The upper tail. For large zz, computing 1−Φ(z)1 - \Phi(z) cancels: in double precision 1−Φ(9)1 - \Phi(9) is exactly 0, while Φˉ(9)=1.1286×10−19\bar\Phi(9) = 1.1286 \times 10^{-19}. Line L7 evaluates 12erfc⁡(z/2)\tfrac12\operatorname{erfc}(z/\sqrt2) directly, which keeps its relative accuracy far into the tail. This is catastrophic cancellation in its simplest form.
  • The sum. A naive running sum of nn numbers has a rounding error that can grow like nn times the unit roundoff times the sum of the absolute values. When the mean is close to μ0\mu_0 and the values are large (a mean of 500.001 tested against 500), this error can be a large part of xˉ−μ0\bar x - \mu_0. The implementation uses an exactly rounded sum (math.fsum); Kahan summation or pairwise summation also work. Subtracting μ0\mu_0 from each value before summing is another remedy.

Properties

  • Exact under its model. For iid normal data with known σ\sigma, size and power are given by closed forms for every nn. Nothing is asymptotic.
  • Uniform p-value. Under a simple null the p-value is uniform on (0,1)(0, 1), because the null distribution is continuous.
  • Optimal. The one-sided test is uniformly most powerful at its level, and the two-sided test is uniformly most powerful unbiased. No other level-α\alpha test of μ=μ0\mu = \mu_0 with known σ\sigma has more power at every alternative in its class.
  • Dual to an interval. The two-sided test at level α\alpha fails to reject μ0\mu_0 exactly when μ0\mu_0 lies in Xˉ±z1−α/2 σ/n\bar X \pm z_{1-\alpha/2}\,\sigma/\sqrt n. For the example this interval is [500.16,505.39][500.16, 505.39], which excludes 500. See test-interval duality.
  • Robust in level for large nn, not for small nn. If the data are not normal but iid with finite variance σ2\sigma^2 (still known), ZZ converges in distribution to N(0,1)N(0, 1) and the size tends to α\alpha. For small nn and skewed data the one-sided size can be far off.
  • Scale and location equivariant. Changing the unit of measurement or shifting all values and μ0\mu_0 together leaves zz and pp unchanged.

Variants and improvements

  • Student's t-test. When σ\sigma is unknown, replace it by the sample standard deviation SS (divisor n−1n - 1). The statistic then has the t distribution with n−1n - 1 degrees of freedom, not N(0,1)N(0, 1). Using the z critical value with SS makes the test anti-conservative for small nn: with n=5n = 5, P(∣T∣≥1.96)≈0.12P(|T| \ge 1.96) \approx 0.12 under the null.
  • Large-sample z-test with estimated σ\sigma. For large nn and any iid data with finite variance, (Xˉ−μ0)/(S/n)(\bar X - \mu_0)/(S/\sqrt n) converges in distribution to N(0,1)N(0, 1), by the central limit theorem and Slutsky's theorem. This is the Wald test for a mean. The size is only near α\alpha.
  • Proportion test with p^\hat p in the standard error. Using p^(1−p^)/n\sqrt{\hat p(1 - \hat p)/n} gives the Wald test for a proportion, whose size and interval coverage are worse than with p0p_0. The version on this page, with p0p_0, is the score test, and inverting it gives the Wilson score interval.
  • Two proportions. The same idea with the pooled estimate of pp under H0H_0 gives the two-proportion z-test. Its square is the chi-square statistic of a 2×22 \times 2 table.
  • Continuity correction. Subtracting 1/21/2 from ∣K−np0∣|K - np_0| moves the size of the proportion test toward the exact binomial test. With small nn, use the binomial test itself.

When to use it

Use the normal-data z-test when σ\sigma really is known from outside the sample: a calibrated instrument, a process with a long stable record, or a simulation where the variance is a design choice. Use the large-sample form for means and proportions when nn is large, and say that the size is approximate. When σ\sigma is estimated from a small or moderate sample, use the t-test, and for a proportion with small nn or extreme p0p_0, use the exact binomial test.

Pitfalls

  • Plugging in SS for σ\sigma with a small sample. The statistic is then t-distributed, and the z critical value rejects too often. The real size is 0.122, about 2.4 times the nominal size, at n=5n = 5 and α=0.05\alpha = 0.05.
  • Computing the p-value as 1−Φ(z)1 - \Phi(z). For z≥8.3z \ge 8.3 this returns 0 in double precision. Report the upper tail with erfc.
  • Reading the asymptotic size as exact. The proportion test at n=50n = 50, p0=1/2p_0 = 1/2 has size 0.065, not 0.05. State the exact size or use an exact test.
  • Choosing the side after seeing the data. A one-sided p-value is half the two-sided one. Picking the side that matches the observed sign doubles the real type I error rate.
  • Treating "not significant" as "no effect". In the example design, a true shift of 2 g is missed 68% of the time. A large p-value says that the data are compatible with H0H_0, and also with many alternatives. Look at the power or the interval.

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.

stdist.pyI0RawGitHub
# 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)
z_core.py 65 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/z-test/. The authors are listed in prov/PZWGTN.jsonl.
"""The one-sample, two-sample and one-proportion z-tests.

Each function returns (z, p): the statistic and its p-value for the chosen
alternative, "two-sided", "greater" (H_1: parameter > null value) or "less".
Upper tails come from erfc, not from 1 - cdf, so small p-values keep their
relative accuracy. The code is in this file and not in z_test.py, because
tools treat a file whose name ends in _test.py as a test file.
"""

import math
from collections.abc import Sequence

from stdist import norm_cdf, norm_sf

ALTERNATIVES = ("two-sided", "greater", "less")


def normal_p_value(z: float, alternative: str = "two-sided") -> float:
    """The p-value of an observed z when Z is standard normal under H_0."""
    if alternative == "two-sided":
        return min(1.0, 2.0 * norm_sf(abs(z)))  # @line L6
    if alternative == "greater":
        return norm_sf(z)  # @line L7
    if alternative == "less":
        return norm_cdf(z)  # @line L8
    raise ValueError(f"alternative must be one of {ALTERNATIVES}")


def z_test(x: Sequence[float], mu0: float, sigma: float,
           alternative: str = "two-sided") -> tuple[float, float]:
    """Test H_0: mu = mu0 for iid N(mu, sigma^2) data with sigma known."""
    n = len(x)  # @line L1
    if n < 1 or sigma <= 0.0:
        raise ValueError("need at least one observation and sigma > 0")
    s = math.fsum(x)  # @line L2
    mean = s / n  # @line L3
    z = (mean - mu0) / (sigma / math.sqrt(n))  # @line L4
    return z, normal_p_value(z, alternative)  # @line L5


def two_sample_z_test(x: Sequence[float], y: Sequence[float], sigma_x: float, sigma_y: float,
                      delta0: float = 0.0, alternative: str = "two-sided") -> tuple[float, float]:
    """Test H_0: mu_x - mu_y = delta0 for two independent normal samples with known sigmas."""
    m, n = len(x), len(y)
    if m < 1 or n < 1 or sigma_x <= 0.0 or sigma_y <= 0.0:
        raise ValueError("need non-empty samples and positive sigmas")
    diff = math.fsum(x) / m - math.fsum(y) / n
    se = math.sqrt(sigma_x * sigma_x / m + sigma_y * sigma_y / n)
    z = (diff - delta0) / se
    return z, normal_p_value(z, alternative)


def proportion_z_test(k: int, n: int, p0: float,
                      alternative: str = "two-sided") -> tuple[float, float]:
    """Large-sample test of H_0: p = p0 from k successes in n Bernoulli trials.

    The standard error uses p0, the value under H_0. The null distribution
    is standard normal only in the limit n -> infinity.
    """
    if n < 1 or not 0 <= k <= n or not 0.0 < p0 < 1.0:
        raise ValueError("need n >= 1, 0 <= k <= n and 0 < p0 < 1")
    z = (k - n * p0) / math.sqrt(n * p0 * (1.0 - p0))
    return z, normal_p_value(z, alternative)
test_z_test.py 113 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/z-test/. The authors are listed in prov/PZWGTN.jsonl.

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

import pytest

from z_test import normal_p_value, proportion_z_test, two_sample_z_test, z_test

PHI = NormalDist()


def test_worked_example() -> None:
    x = [502, 498, 505, 503, 501, 507, 499, 504, 506]
    z, p = z_test(x, 500.0, 4.0)
    # X-bar = 4525/9, so z = (4525/9 - 500) / (4/3) = 25/12 exactly.
    assert abs(z - 25.0 / 12.0) < 1e-12
    assert abs(p - 2.0 * (1.0 - PHI.cdf(25.0 / 12.0))) < 1e-12
    assert abs(z_test(x, 500.0, 4.0, "greater")[1] - p / 2.0) < 1e-15
    assert abs(z_test(x, 500.0, 4.0, "less")[1] - (1.0 - p / 2.0)) < 1e-12


def test_statistic_against_fractions() -> None:
    rng = random.Random(7)
    for _ in range(50):
        n = rng.randint(1, 12)
        x = [rng.randint(-50, 50) for _ in range(n)]
        mu0, sigma = rng.randint(-5, 5), rng.randint(1, 9)
        z, _ = z_test(x, mu0, sigma)
        exact = (Fraction(sum(x), n) - mu0) / sigma  # z / sqrt(n)
        assert abs(z / math.sqrt(n) - float(exact)) < 1e-12


def test_small_p_values_keep_relative_accuracy() -> None:
    # P(Z > 9) = 1.1285884059538e-19; 1 - cdf would give 0.
    assert abs(normal_p_value(9.0, "greater") / 1.1285884059538408e-19 - 1.0) < 1e-12
    assert normal_p_value(-9.0, "less") > 0.0
    assert normal_p_value(0.0) == 1.0
    with pytest.raises(ValueError):
        normal_p_value(1.0, "both")


def test_monte_carlo_size_and_uniform_p_values() -> None:
    rng = random.Random(2024)
    r, n = 4000, 10
    ps = [z_test([rng.gauss(3.0, 2.0) for _ in range(n)], 3.0, 2.0)[1] for _ in range(r)]
    for u in [0.01, 0.05, 0.25, 0.5, 0.9]:
        frac = sum(p <= u for p in ps) / r
        assert abs(frac - u) < 4.0 * math.sqrt(u * (1.0 - u) / r)


def test_monte_carlo_power_matches_closed_form() -> None:
    rng = random.Random(11)
    r, n, shift = 4000, 16, 0.5  # mu - mu0 = 0.5 sigma, so lambda = 2
    rejections = sum(
        z_test([rng.gauss(0.5, 1.0) for _ in range(n)], 0.0, 1.0)[1] <= 0.05 for _ in range(r)
    )
    lam = shift * math.sqrt(n)
    c = PHI.inv_cdf(0.975)
    power = PHI.cdf(lam - c) + PHI.cdf(-lam - c)
    assert abs(rejections / r - power) < 4.0 * math.sqrt(power * (1.0 - power) / r)


def test_two_sample_size() -> None:
    rng = random.Random(5)
    r = 3000
    rejections = 0
    for _ in range(r):
        x = [rng.gauss(1.0, 3.0) for _ in range(4)]
        y = [rng.gauss(1.0, 0.5) for _ in range(20)]
        rejections += two_sample_z_test(x, y, 3.0, 0.5)[1] <= 0.05
    assert abs(rejections / r - 0.05) < 4.0 * math.sqrt(0.05 * 0.95 / r)
    z, _ = two_sample_z_test([3.0, 5.0], [1.0], 1.0, 2.0, delta0=1.0)
    assert abs(z - (4.0 - 1.0 - 1.0) / math.sqrt(0.5 + 4.0)) < 1e-12


def exact_size(n: int, p0: Fraction, alpha: float = 0.05) -> Fraction:
    """P_(p0)(reject) for the proportion z-test, by summing binomial terms exactly."""
    return sum(
        (math.comb(n, k) * p0**k * (1 - p0) ** (n - k)
         for k in range(n + 1) if proportion_z_test(k, n, float(p0))[1] <= alpha),
        Fraction(0),
    )


def test_proportion_rejection_region_by_enumeration() -> None:
    # n = 100, p0 = 1/2: z = (k - 50)/5, so the test rejects iff |k - 50| >= 10.
    rejected = [k for k in range(101) if proportion_z_test(k, 100, 0.5)[1] <= 0.05]
    assert rejected == list(range(0, 41)) + list(range(60, 101))
    size = exact_size(100, Fraction(1, 2))
    tail = sum(Fraction(math.comb(100, k), 2**100) for k in range(60, 101))
    assert size == 2 * tail
    assert abs(float(size) - 0.05688793364098079) < 1e-15


def test_proportion_size_is_only_near_alpha() -> None:
    # The exact size of the asymptotic test, by enumeration.
    assert abs(float(exact_size(20, Fraction(1, 2))) - 0.04138946533203125) < 1e-15
    assert abs(float(exact_size(50, Fraction(1, 2))) - 0.06490864707227217) < 1e-15
    assert abs(float(exact_size(30, Fraction(1, 10))) - 0.025826788661909874) < 1e-12
    assert abs(float(exact_size(1000, Fraction(1, 2))) - 0.05) < 0.005


def test_bad_input() -> None:
    with pytest.raises(ValueError):
        z_test([], 0.0, 1.0)
    with pytest.raises(ValueError):
        z_test([1.0], 0.0, 0.0)
    with pytest.raises(ValueError):
        proportion_z_test(3, 2, 0.5)
z_test.py 8 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/z-test/. The authors are listed in prov/PZWGTN.jsonl.
"""Entry point named after the slug. The code lives in z_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""

from z_core import ALTERNATIVES, normal_p_value, proportion_z_test, two_sample_z_test, z_test

__all__ = ["ALTERNATIVES", "normal_p_value", "proportion_z_test", "two_sample_z_test", "z_test"]

History

Fisher's Statistical Methods for Research Workers (1925) gave tables of the normal distribution in a form for testing and named 1.96, "or nearly 2", as the deviation exceeded with probability 0.05. Comparing a standardized mean or proportion with the normal law is older: it rests on the normal approximation and the central limit theorem. In the Neyman-Pearson theory of the 1930s, the one-sided z-test became the standard example of a uniformly most powerful test.

References

  1. George Casella and Roger L. Berger, Statistical Inference, second edition, Duxbury, 2002, Section 8.3.1 (error probabilities and the power function, with the normal mean test), Section 8.3.4 (p-values) and Section 10.3 (large-sample tests)
  2. E. L. Lehmann and Joseph P. Romano, Testing Statistical Hypotheses, third edition, Springer, 2005, Chapter 3 (uniformly most powerful one-sided tests) and Chapter 4 (unbiased tests, the two-sided case)
  3. Larry Wasserman, All of Statistics, Springer, 2004, Section 10.1 (the Wald test, with the test of a mean and of a proportion) and Section 10.2 (p-values)
  4. Ronald A. Fisher, Statistical Methods for Research Workers, Oliver and Boyd, 1925, online text of the first edition, Chapter III, Section 12 (the normal distribution and the 5% point 1.96)

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