Algorithmcore
Anderson-Darling test
Also called Anderson-Darling statistic.
A goodness-of-fit test by a weighted squared distance between the empirical and the model CDF, with weights that stress the tails.
- Time
- Θ(b n log n) worstΘ(n log n) best
- Space
- Θ(n) extra
- Where
- b = the number of simulated samples for the Monte Carlo p-value; n = the sample size
- Model
- Real RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Theodore W. Anderson, Donald A. Darling, 1952
The Anderson-Darling test checks whether a sample comes from a given continuous distribution function . Its statistic is
the squared distance between the empirical distribution function and , with each point weighted by the inverse of the variance of . The weight is large in both tails, so the test reacts to differences in the tails that the Kolmogorov-Smirnov test misses. After sorting, is a sum of logarithms. Its null law does not depend on , and the page takes the p-value from the limit law or from a Monte Carlo simulation of uniform samples.
In plain words
A model says how the data should spread out. Compare the share of data below each point with the share that the model expects. A gap of a given size is more surprising in the tails than in the middle, because few points fall in the tails, so the shares there should match closely. The test squares each gap, divides it by how much the gap usually varies at that point, and adds the results over the whole range.
A large total means that the data and the model disagree somewhere, often in a tail. The same table serves every continuous model, because a fixed change of scale turns any such model into the uniform model. For a small sample one can also simulate many uniform samples and count how often their total is at least as large.
The problem
Model. are independent with an unknown distribution function . is a fully specified continuous distribution function.
Hypotheses. : . : .
Statistic. With for the sorted data,
It equals the integral above. If some is 0 or 1, the integral is infinite.
Null distribution. Under , are the order statistics of independent uniforms, so the law of depends on and not on . For , and for . For larger the exact law has no closed form. As , converges in law to with independent standard normal ; its mean is 1. The page uses this limit, which is asymptotic, or a Monte Carlo estimate of the exact law.
P-values. The test is one-sided in : large values speak against , and no doubling rule applies. The asymptotic p-value is , with the distribution function of . The Monte Carlo p-value is , where is the number of simulated uniform samples of size whose statistic is at least the observed one.
Rejection rule and size. Reject at level when . The Monte Carlo p-value gives size at most for every and . The percentiles of the limit law are (50%), (90%), (95%), (97.5%) and (99%). The limit test is close to the exact one already for small . In a Monte Carlo run with uniform samples per case, the simulated 95% points were , and for , and (seeds 71, 72 and 73), and the limit test at rejected , and of the samples.
Sensitivity and power. The test is consistent against every fixed . The weight makes it more sensitive than the Kolmogorov-Smirnov test to differences in the tails and in spread. In a Monte Carlo run against with , samples per case and , both tests on the same samples gave these rejection rates:
| Data | Seed | Anderson-Darling | Kolmogorov-Smirnov |
|---|---|---|---|
| 62 | |||
| 63 | |||
| Student with 3 degrees of freedom | 65 | ||
| 66 |
The last row shows a weak point: against a smaller spread, a sample of 20 points has no values far in the tails, and the test has almost no power.
The algorithm
ANDERSON-DARLING(x_1, ..., x_n, F_0, method, b)- 1
u ← the values F_0(x_i), sorted - 2
if u_1 = 0 or u_n = 1 then return ∞, 0 - 3
S ← sum over i = 1, ..., n of (2i - 1) · (ln u_i + ln(1 - u_(n+1-i))) - 4
A² ← -n - S/n - 5
if method = asymptotic then return A², 1 - ADINF(A²) - 6
c ← number of j = 1, ..., b where A² of a sorted sample of n uniforms ≥ A² - 7
return A², (1 + c)/(1 + b)
Lines L1 to L4 compute the statistic. The code uses log1p for , so values of near 0 keep their digits, and a compensated sum for . evaluates the series of Anderson and Darling (1954) in the form of Marsaglia and Marsaglia (2004),
The terms fall fast, and the code stops when a term is below . Each integral uses Simpson's rule on , where is chosen so that the integrand is below beyond . Lines L6 and L7 simulate the exact null law with a seeded generator; this is a Monte Carlo test, and the p-value has a random part of standard deviation about .
Example
The model is the exponential law with mean 1, , and the data are those of the Kolmogorov-Smirnov page: . Line L1 gives
The first term of is , which pairs the smallest and the largest value. In total , so . The limit law gives . The Monte Carlo p-value with and seed 7 is . The Kolmogorov-Smirnov test gave on the same data, so both tests accept the model. Against the exponential law with mean , and .
One observation. For the smallest value of is , at . The formula above gives and .
Correctness
The proof is in proofs/correctness.md. On each interval between two sorted values, is a constant , and the integrand is in the variable . Integrating these pieces and collecting the logarithms by summation by parts gives the formula of lines L3 and L4. The probability integral transform shows that the null law of is that of uniform samples, so the simulated values in line L6 have the exact null law. The observed and the simulated values are then exchangeable, and the rank argument gives for the p-value of line L7. The asymptotic p-value relies on the limit law, which we cite.
Proof: The Anderson-Darling computing formula and the validity of its p-valuesfull
We use the pseudocode of the page. is continuous, are the sorted values from line L1, and we set , and .
Claim 1 (the computing formula). If and , then
If or , the integral is infinite.
Proof. Substitute . For continuous , is uniform under the measure , and , where is the empirical distribution function of the . So the integral is . On , , and
which one checks by putting the right side over the common denominator : the numerator is . On the first piece , and on the last piece , so the terms near and near do not appear there, and every piece has a finite integral when and . If , the piece has and ; the case is the same by symmetry.
The terms add up to , which gives after the factor . The terms give, by summation by parts,
because and . The terms give
because and . With , , so the last sum is . Multiply by and add. Ties among the give empty pieces and change nothing.
So lines L2 to L4 return , with in line L2.
Claim 2 (distribution-free). Under , has the law of the order statistics of independent uniforms on , so the law of depends only on .
Proof. For continuous , for , so each is uniform, the values are independent, and sorting commutes with the nondecreasing map . By Claim 1, is a function of these values.
Claim 3 (the Monte Carlo p-value). Under , the p-value of line L7 satisfies for every and every .
Proof. Let be the observed statistic and the simulated ones. By Claim 2 the samples of line L6 have the null law of the data, so are independent and identically distributed, hence exchangeable. Let , so . For an integer , let . If is not empty, take with the smallest . Every has , so . By exchangeability, . With , ; if the event is empty. Ties among the are allowed.
The random part of the Monte Carlo p-value does not affect this bound: it holds for the joint law of the data and the simulation.
Claim 4 (the asymptotic p-value). As , converges in law to , and the series for is its distribution function. We cite both results from Anderson and Darling (1952, 1954) and do not prove them here. The p-value therefore has size that tends to , and the page reports Monte Carlo sizes for small .
The numerical integrals. The integrand of the -th term is at most , because . The code takes , so beyond the integrand is below and falls like a Gaussian. Simpson's rule on with 4000 steps has an error of order times the fourth derivative of a smooth integrand. The tests check the result against the published percentiles and to five digits, and check that the mean of the limit law is 1.
Cost. Line L1 sorts values. Lines L2 to L4 take . Line L6 sorts samples of size .
Complexity
Line L1 sorts in and lines L2 to L4 are linear, so the statistic costs time and space. The asymptotic p-value costs a fixed amount of work for a given accuracy: a few terms of the series, each with a fixed number of Simpson steps. The Monte Carlo p-value sorts samples of size , which costs time and extra space.
Properties
- Distribution-free. For continuous the null law of depends only on .
- Invariant. does not change under an increasing transformation applied to both the data and the model.
- Tail weight. The variance of is under . Dividing by it gives every point the same null variance, so a gap in a tail counts as much as a gap of the same number of standard deviations in the middle.
- Structure of the limit. The limit comes from the Karhunen-Loeve expansion of the weighted Brownian bridge , whose eigenfunctions are built from Legendre polynomials.
- Parameters must be fixed in advance. In a Monte Carlo run with normal data, , samples and seed 67, the test with the estimated mean and standard deviation and the limit 95% point rejected none of the samples.
Variants and improvements
- Estimated parameters. For normal, exponential and other families, tables for with estimated parameters exist, often for a modified statistic, times a factor that depends on . A parametric bootstrap gives the null law for any model.
- Finite-n correction. Marsaglia and Marsaglia (2004) give a correction to the limit law for finite .
- Cramer-von Mises. The same integral without the weight gives the Cramer-von Mises statistic , which is closer to the Kolmogorov-Smirnov test in where it looks.
- k samples. Scholz and Stephens extended the statistic to compare several samples, with a permutation null law as for a permutation test.
- Other tests. For normality the Shapiro-Wilk test is a strong alternative; for counts in classes, the chi-squared goodness-of-fit test.
When to use it
Use it to test a fully specified continuous model when differences in the tails matter, as in risk models, reliability, or before a method that relies on the tails of a model. With estimated parameters, use the matching table or a parametric bootstrap. Look at a Q-Q plot as well, to see where the data and the model differ.
Pitfalls
- Estimated parameters. Using the standard table after estimating the parameters makes the test far too conservative; in the run above it never rejected at .
- Values at the edge of the support. If is 0 or 1, as for a value outside the support of the model, is infinite. In floating point a value far in a tail can round to 1; compute directly from the survival function of the model when possible.
- Discrete data. Ties and jumps in change the null law; the continuous tables do not apply.
- Little power against a smaller spread. With the test rejected against in only of samples.
- Old tables. Older tables list for the 1% point of the limit law. The series gives , and the 99% point is (Marsaglia and Marsaglia 2004).
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
# Part of https://algorithm.tamnd.com/anderson-darling-test/. The authors are listed in prov/7ZCNKW.jsonl.
import math
import random
from typing import Callable
def ad_statistic_u(u: list[float]) -> float:
"""A^2 from the sorted values u_1 <= ... <= u_n of F_0 at the data."""
n = len(u)
if u[0] <= 0.0 or u[-1] >= 1.0: # @line L2
return math.inf
s = math.fsum((2 * i - 1) * (math.log(u[i - 1]) + math.log1p(-u[n - i]))
for i in range(1, n + 1)) # @line L3
return -n - s / n # @line L4
def ad_statistic(x: list[float], cdf: Callable[[float], float]) -> float:
"""The Anderson-Darling statistic A^2 of the sample x against the CDF F_0."""
return ad_statistic_u(sorted(cdf(v) for v in x)) # @line L1
def adinf_cdf(z: float, steps: int = 4000) -> float:
"""P(A^2_inf <= z) for the limit law A^2_inf = sum_j Z_j^2 / (j (j + 1)).
Uses the series of Anderson and Darling (1954), in the form
(sqrt(2 pi)/z) sum_j C(-1/2, j) (4j + 1) exp(-a_j) I_j with a_j = (4j + 1)^2 pi^2 / (8 z)
and I_j = integral_0^inf exp(z / (8 (w^2 + 1)) - a_j w^2) dw, each I_j by Simpson's
rule on [0, W] where the integrand is below exp(-40) beyond W.
"""
if z <= 0.0:
return 0.0
total, coef, j = 0.0, 1.0, 0
while True:
a = (4 * j + 1) ** 2 * math.pi**2 / (8 * z)
width = math.sqrt((40.0 + z / 8.0) / a)
h = width / steps
acc = 0.0
for i in range(steps + 1):
w = i * h
f = math.exp(z / (8.0 * (w * w + 1.0)) - a * w * w)
acc += f if i in (0, steps) else (4.0 * f if i % 2 else 2.0 * f)
term = coef * (4 * j + 1) * math.exp(-a) * acc * h / 3.0
total += term
if abs(term) < 1e-17 and j > 2:
break
j += 1
coef *= -(2 * j - 1) / (2 * j)
return min(1.0, max(0.0, math.sqrt(2 * math.pi) / z * total))
def ad_test(
x: list[float],
cdf: Callable[[float], float],
method: str = "asymptotic",
b: int = 9999,
rng: random.Random | None = None,
) -> tuple[float, float]:
"""Anderson-Darling test of H0: the data have the continuous, fully specified CDF F_0.
Returns (A^2, p). method "asymptotic" uses the limit law; method
"monte-carlo" simulates b samples of n uniforms (the exact null law of
A^2 for every continuous F_0) and returns (1 + count) / (1 + b), where
count is the number of simulated values at least the observed one.
"""
if not x:
raise ValueError("need at least one observation")
a2 = ad_statistic(x, cdf)
if math.isinf(a2):
return a2, 0.0
if method == "asymptotic": # @line L5
return a2, max(0.0, 1.0 - adinf_cdf(a2))
if method != "monte-carlo":
raise ValueError("unknown method")
if rng is None:
raise ValueError("pass rng = random.Random(seed) for the Monte Carlo p-value")
n = len(x)
count = 0
for _ in range(b): # @line L6
sim = sorted(rng.random() for _ in range(n))
if ad_statistic_u(sim) >= a2:
count += 1
return a2, (1 + count) / (1 + b) # @line L7
anderson_darling_test.py 8 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/anderson-darling-test/. The authors are listed in prov/7ZCNKW.jsonl.
"""Entry point named after the slug. The code lives in ad_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""
from ad_core import ad_statistic, ad_statistic_u, ad_test, adinf_cdf
__all__ = ["ad_statistic", "ad_statistic_u", "ad_test", "adinf_cdf"]
test_anderson_darling_test.py 110 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/anderson-darling-test/. The authors are listed in prov/7ZCNKW.jsonl.
import math
import random
import pytest
from anderson_darling_test import ad_statistic, ad_statistic_u, ad_test, adinf_cdf
X = [0.42, 0.06, 1.95, 0.88, 0.13, 3.10, 0.27, 0.71, 0.09, 0.35]
def exp_cdf(v: float) -> float:
return 1.0 - math.exp(-v) if v > 0 else 0.0
def a2_by_integration(u: list[float]) -> float:
"""n times the integral of (F_n(t) - t)^2 / (t (1 - t)) over (0, 1), piece by piece.
On a piece where F_n = c the integrand is c^2/t + (1 - c)^2/(1 - t) - 1, which has
a closed-form integral. This uses the definition, not the sum of the code."""
n = len(u)
pts = [0.0] + sorted(u) + [1.0]
total = 0.0
for i in range(n + 1):
a, b, c = pts[i], pts[i + 1], i / n
part = -(b - a)
if c > 0:
part += c * c * (math.log(b) - math.log(a))
if c < 1:
part += (1 - c) ** 2 * (math.log1p(-a) - math.log1p(-b))
total += part
return n * total
def test_page_example() -> None:
assert ad_statistic(X, exp_cdf) == pytest.approx(0.79588947, abs=1e-7)
assert ad_test(X, exp_cdf)[1] == pytest.approx(0.48400265, abs=1e-6)
assert ad_test(X, exp_cdf, "monte-carlo", b=9999, rng=random.Random(7))[1] == pytest.approx(0.4813, abs=1e-12)
def test_statistic_against_the_integral() -> None:
rng = random.Random(1)
for _ in range(300):
u = [rng.random() for _ in range(rng.randint(1, 15))]
assert ad_statistic_u(sorted(u)) == pytest.approx(a2_by_integration(u), rel=1e-9, abs=1e-12)
def test_one_observation_law() -> None:
# n = 1: A^2 = -1 - ln u - ln(1 - u), so P(A^2 <= a) = sqrt(1 - 4 e^{-(1 + a)}) for a >= ln 4 - 1.
grid = 200000
values = [ad_statistic_u([(i + 0.5) / grid]) for i in range(grid)]
for a in (0.5, 1.0, 2.0, 3.0):
share = sum(v <= a for v in values) / grid
assert share == pytest.approx(math.sqrt(1 - 4 * math.exp(-(1 + a))), abs=1e-4)
assert min(values) == pytest.approx(math.log(4) - 1, abs=1e-9)
def test_limit_law_percentiles() -> None:
# Percentiles of the limit law (Marsaglia and Marsaglia 2004): 2.4924 and 3.8781.
assert adinf_cdf(2.4924) == pytest.approx(0.95, abs=1e-5)
assert adinf_cdf(3.8781) == pytest.approx(0.99, abs=1e-5)
assert adinf_cdf(3.857) == pytest.approx(0.98976, abs=1e-5) # the 1954 value is a bit low
assert adinf_cdf(0.0) == 0.0
assert adinf_cdf(40.0) == pytest.approx(1.0, abs=1e-12)
def test_limit_law_mean_is_one() -> None:
# The limit is sum_j Z_j^2 / (j (j + 1)), with mean sum_j 1 / (j (j + 1)) = 1.
h, top = 0.04, 30.0
steps = int(top / h)
acc = 0.0
for i in range(steps + 1):
f = 1.0 - adinf_cdf(i * h, steps=400)
acc += f if i in (0, steps) else (4.0 * f if i % 2 else 2.0 * f)
assert acc * h / 3.0 == pytest.approx(1.0, abs=2e-3)
def test_monte_carlo_p_value_is_valid() -> None:
rng = random.Random(3)
r, alpha = 400, 0.1
hits = 0
for _ in range(r):
x = [rng.random() for _ in range(8)]
hits += ad_test(x, lambda v: v, "monte-carlo", b=99, rng=rng)[1] <= alpha
assert hits / r <= alpha + 4 * math.sqrt(alpha * (1 - alpha) / r)
def test_asymptotic_size_monte_carlo() -> None:
rng = random.Random(4)
r, alpha = 4000, 0.05
crit = 2.4924 # the 95% point of the limit law
hits = sum(ad_statistic_u(sorted(rng.random() for _ in range(10))) >= crit for _ in range(r))
assert abs(hits / r - alpha) <= 4 * math.sqrt(alpha * (1 - alpha) / r)
def test_invariance_under_monotone_maps() -> None:
y = [math.log(v) for v in X] # if X has CDF F_0, log X has CDF F_0(e^t)
assert ad_statistic(y, lambda t: exp_cdf(math.exp(t))) == pytest.approx(ad_statistic(X, exp_cdf), rel=1e-12)
def test_edges() -> None:
with pytest.raises(ValueError):
ad_test([], exp_cdf)
with pytest.raises(ValueError):
ad_test(X, exp_cdf, "monte-carlo")
with pytest.raises(ValueError):
ad_test(X, exp_cdf, "exact")
assert ad_test([-1.0, 0.5], exp_cdf) == (math.inf, 0.0) # a point where F_0 = 0
History
Theodore Anderson and Donald Darling (1952) studied a family of distances between the empirical and the model distribution function, weighted by a function of , and found their limit laws through the eigenvalues of the weighted Brownian bridge. In a short paper in 1954 they singled out the weight , gave the computing formula with logarithms, and gave a table of the limit law from a series. Stephens later gave modified statistics and tables for the case of estimated parameters. Marsaglia and Marsaglia (2004) gave an accurate program for the limit law and a correction for finite samples.
References
- T. W. Anderson and D. A. Darling, Asymptotic theory of certain goodness of fit criteria based on stochastic processes, Annals of Mathematical Statistics 23(2), 1952, pp. 193 to 212 (the weighted criteria, the weight 1/(F(1 - F)), and the limit law as a weighted sum of chi-square variables)
- T. W. Anderson and D. A. Darling, A test of goodness of fit, Journal of the American Statistical Association 49, 1954, pages 765 to 769, the computing formula for A^2 from the sorted values and the series for the limit law with its percentage points
- George Marsaglia and John Marsaglia, Evaluating the Anderson-Darling distribution, Journal of Statistical Software 9(2), 2004, the accurate evaluation of the limit law and its percentiles, and a correction for finite n
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 7ZCNKW Edit this page History Report an error Markdown