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
- Model
- Real RAM
- Properties
- deterministicexactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 , the null distribution is exactly for every sample size, and the test has size exactly . For a proportion, and for any mean when 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 . 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 iid , with known and unknown. The null hypothesis is . The alternative is two-sided, , or one-sided, ("greater") or ("less"). For a one-sided alternative the null can also be the composite (or ), with the same test.
Statistic. With the sample mean ,
Null distribution. Exact: under for every . In general with .
Rejection rule and size. At level , with the lower quantiles of : reject when (two-sided), ("greater") or ("less"). The size equals exactly. For , and .
p-value. With the observed value and the upper tail: ("greater"), ("less"), and (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 is, for the two-sided test,
and 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 and with known and , with and ; it is exact. The one-proportion test takes successes in Bernoulli trials (binomial distribution), , and , with the standard error computed at . Its null distribution is only asymptotically, so its size is only near .
The algorithm
Z-TEST(x[1..n], μ₀, σ, alternative) ▷ σ > 0 known, n ≥ 1- 1
n ← the length of x - 2
s ← x[1] + x[2] + ... + x[n] ▷ an accurate sum, see below - 3
x̄ ← s / n - 4
z ← (x̄ − μ₀) / (σ / √n) - 5
return (z, NORMAL-P-VALUE(z, alternative)) NORMAL-P-VALUE(z, alternative)- 6
if alternative = two-sided then return min(1, 2 · Φ̄(|z|)) - 7
if alternative = greater then return Φ̄(z) - 8
if alternative = less then return Φ(z)
Here and , where erfc is the complementary error function of the math library. The test rejects at level when the returned , 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 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: g. Nine packs weigh
Test against at .
| step | value |
|---|---|
| L2: | |
| L3: | |
| L4: | |
| L4: | |
| L6: |
Since (equivalently ), the test rejects at the 5% level. The one-sided p-value for is , half of the two-sided one. The test does not reject at the 1% level, where the two-sided critical value is .
The power of this design (, , two-sided, ) at a few true means:
| true | power | |
|---|---|---|
| 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 " means. With and , , and the two-sided test at rejects exactly when . The exact size, a sum of binomial probabilities, is , not . More exact sizes of the same nominal 5% test:
| 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 because is discrete, and it is far from when is small. The exact binomial test has size at most for every .
Correctness
Under the normal model, is a sum of independent normals divided by , so it is normal with mean and variance . Then is an affine function of a normal variable with mean and variance 1, which is under . Each p-value of lines L6 to L8 is the probability under of a statistic at least as extreme as , and since is continuous and strictly increasing, for each , so the size is exactly . For the composite one-sided null , the rejection probability increases in , so its maximum over the null is at . The proportion statistic is a standardized sum of iid Bernoulli variables and converges in distribution to by the central limit theorem, so its size tends to . 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 , that the rejection rules have size exactly , that the p-values are the stated tail probabilities and are uniform under , and that the proportion version has size that tends to . is the standard normal CDF and is its lower -quantile.
Lemma 1 (the null distribution). Let be iid with known. Then has the distribution with . In particular exactly when , for every .
Proof. The moment generating function of is . By independence, the moment generating function of is , which is that of . A moment generating function that is finite near 0 fixes the distribution, so . An affine map of a normal is , by the same argument. With and , has mean and variance .
Lemma 2 (the two-sample statistic). Let be iid and iid , the two samples independent, with known. Then when .
Proof. By Lemma 1, and , and they are independent. The product of their moment generating functions at and shows . Standardize as in Lemma 1.
Lemma 3 (p-values and size). Let under , and let be the observed value. The p-values computed by NORMAL-P-VALUE are for "greater", for "less" and for "two-sided". For each, for every . So the rule "reject when " has size exactly .
Proof. , which the code computes as ; this is the same function, since and . . By symmetry of the standard normal, , which is at most 1 because ; the min with 1 only guards rounding. For uniformity, take "greater": , and is continuous and strictly decreasing, so , which has probability . For "two-sided", , which has probability . "less" is the mirror image of "greater".
So "reject when " is the same as "reject when " ("greater"), "" ("less") or "" ("two-sided").
Lemma 4 (the one-sided test is valid on the composite null). For against , the rule "reject when " has size exactly .
Proof. By Lemma 1, , which increases in and so in . Its supremum over is its value at , which is .
Lemma 5 (the power function). The two-sided test at level rejects with probability . It is even in , equals at , and increases in , so the test is unbiased.
Proof. By Lemma 1, with , and . The sum is even in . Its derivative in is , where is the standard normal density. For and , , so and the derivative is positive.
Lemma 6 (the proportion test is asymptotic). Let with fixed, and . Then converges in distribution to , and the size of each rule of Lemma 3 tends to as .
Proof. is a sum of iid Bernoulli() variables with mean and variance , so the central limit theorem gives the convergence in distribution. The limit CDF is continuous, so for each fixed , and the same for the lower and the two-sided rules.
The convergence of Lemma 6 is not uniform in : for fixed , the size can be far from when is small. For each finite the size is a sum of binomial terms, which the tests compute exactly.
Termination. Z-TEST makes one pass over the observations and then a constant number of operations, so it stops after steps.
Theorem. Under the model of Lemma 1 (or Lemma 2), Z-TEST returns the statistic and the p-value , and rejecting when gives a test of size exactly , for every . The proportion version has size that tends to .
Proof. Lemmas 1 to 4 for the normal versions, and Lemma 6 for the proportion version.
Complexity
On a real RAM, lines L1 to L3 make additions and one division, line L4 a constant number of operations, and lines L6 to L8 one evaluation of erfc. So the time is and the extra space is . The test is online: the running sum can take one observation at a time, and is available after each one. The proportion form needs only and , so it costs after counting.
Numerical stability. Two places lose accuracy if they are written carelessly.
- The upper tail. For large , computing cancels: in double precision is exactly 0, while . Line L7 evaluates 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 numbers has a rounding error that can grow like times the unit roundoff times the sum of the absolute values. When the mean is close to and the values are large (a mean of 500.001 tested against 500), this error can be a large part of . The implementation uses an exactly rounded sum (math.fsum); Kahan summation or pairwise summation also work. Subtracting from each value before summing is another remedy.
Properties
- Exact under its model. For iid normal data with known , size and power are given by closed forms for every . Nothing is asymptotic.
- Uniform p-value. Under a simple null the p-value is uniform on , 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- test of with known has more power at every alternative in its class.
- Dual to an interval. The two-sided test at level fails to reject exactly when lies in . For the example this interval is , which excludes 500. See test-interval duality.
- Robust in level for large , not for small . If the data are not normal but iid with finite variance (still known), converges in distribution to and the size tends to . For small 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 together leaves and unchanged.
Variants and improvements
- Student's t-test. When is unknown, replace it by the sample standard deviation (divisor ). The statistic then has the t distribution with degrees of freedom, not . Using the z critical value with makes the test anti-conservative for small : with , under the null.
- Large-sample z-test with estimated . For large and any iid data with finite variance, converges in distribution to , by the central limit theorem and Slutsky's theorem. This is the Wald test for a mean. The size is only near .
- Proportion test with in the standard error. Using gives the Wald test for a proportion, whose size and interval coverage are worse than with . The version on this page, with , is the score test, and inverting it gives the Wilson score interval.
- Two proportions. The same idea with the pooled estimate of under gives the two-proportion z-test. Its square is the chi-square statistic of a table.
- Continuity correction. Subtracting from moves the size of the proportion test toward the exact binomial test. With small , use the binomial test itself.
When to use it
Use the normal-data z-test when 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 is large, and say that the size is approximate. When is estimated from a small or moderate sample, use the t-test, and for a proportion with small or extreme , use the exact binomial test.
Pitfalls
- Plugging in for 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 and .
- Computing the p-value as . For this returns 0 in double precision. Report the upper tail with erfc.
- Reading the asymptotic size as exact. The proportion test at , 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 , 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.
# 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
- 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)
- 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)
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag PZWGTN Edit this page History Report an error Markdown