Algorithmcore
Shapiro-Wilk test
Also called Shapiro-Wilk W test.
Tests normality by the squared correlation of the ordered sample with weights built from the means and covariances of normal order statistics. It is a powerful omnibus test.
- Time
- Θ(n log n) worst · best
- Space
- Θ(n) extra
- Where
- n = the sample size
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Samuel S. Shapiro, Martin B. Wilk, 1965
The Shapiro-Wilk test checks whether a sample comes from some normal distribution, with the mean and variance unknown. It sorts the sample and measures how well the sorted values lie on a straight line against a fixed set of weights , which come from the means and covariances of the order statistics of a standard normal sample. The statistic is the squared correlation between the sorted sample and the weights. It is at most 1, and small values are evidence against normality. itself is computed exactly. The p-value comes from a normalizing transform by Royston, which is an approximation for every ; for the null distribution of is known exactly. In power studies it is among the best general tests of normality.
In plain words
Sort the data. If the data are normal, the sorted values plotted against the values that a normal sample of the same size would have on average fall close to a straight line. The test turns "how straight is this line" into one number between 0 and 1, where 1 means a perfect line. The weights that define the line also take into account that neighboring sorted values are related. Because the number is a correlation, it does not change when you shift the data or change the unit. A number much below what normal samples of the same size give is evidence that the data are not normal. A table or a formula turns the number into a p-value.
The problem
Model and hypotheses. The data are iid from a continuous distribution , with . The null hypothesis is that is normal with some mean and some variance , both unknown. The alternative is every other . It is a composite null, and the test is omnibus: it does not target one kind of departure.
Statistic. Let be the sorted sample. Let be the expected values of the order statistics of iid standard normal variables, and their covariance matrix. The weights are
The weights are antisymmetric, , so , and . Thus is the squared correlation between and . The vector is proportional to the coefficients of the generalized least squares estimate of from the ordered sample, so the numerator is a constant times the square of that estimate, and the denominator is times the sample variance.
Null distribution. is location and scale invariant, so under its law depends on only. For it is exact: for . For there is no closed form. Royston fitted a transform whose null law is close to normal, with mean and standard deviation given as polynomials in or in . This is an empirical fit to simulated values. It is not a theorem.
Rejection rule and size. Reject at level when , that is when is small. For the size is exactly . For the size is close to but not exactly . The Monte Carlo sizes below are measured, not proved.
p-value. , a lower tail of , which is the upper tail of the normal approximation of : .
Sensitivity and power. The test detects skewness and heavy or light tails, and it detects skewness best. In a seeded simulation with 2000 samples for each case, the power at 5% against exponential data was 0.07, 0.17, 0.45, 0.83 and 0.999 for , and against uniform data it was 0.06, 0.06, 0.07, 0.21 and 0.75. With small the test cannot see much. With very large it rejects for departures from normality too small to matter.
The algorithm
SHAPIRO-WILK(x₁, …, xₙ) ▷ 3 ≤ n ≤ 5000, not all equal- 1
y ← x sorted in increasing order - 2
a ← Royston coefficients for n ▷ antisymmetric, Σaᵢ² = 1; exact ±√½ for n = 3 - 3
ȳ ← Σ yᵢ / n; SS ← Σ (yᵢ − ȳ)² - 4
b ← Σ_{i=1}^{⌊n/2⌋} a_{n+1−i} (y_{n+1−i} − yᵢ) ▷ equals Σ aᵢ yᵢ - 5
W ← min(b²/SS, 1) - 6
if n = 3 then return (W, (6/π)(arcsin √W − π/3)) ▷ exact - 7
if n ≤ 11 then γ ← −2.273 + 0.459 nif log(1 − W) ≥ γ then return (W, 0)t ← −log(γ − log(1 − W)); μ, σ ← polynomials in nelset ← log(1 − W); μ, σ ← polynomials in log n- 8
z ← (t − μ)/σ - 9
return (W, 1 − Φ(z))
The coefficients (line L2). The exact needs the covariance matrix of normal order statistics, which has no closed form. Royston's approximation, in the form of Algorithm AS R94, uses Blom's scores in place of . With and ,
and for also by a second polynomial with constants . The middle weights are , with chosen so that , and the lower half is the mirror image. The mean and log standard deviation of are
for , and, with ,
for .
Example
Eleven measurements. Take , already sorted. Then and . Line L4 pairs the largest value with the smallest, the second largest with the second smallest, and so on:
| product | |||
|---|---|---|---|
| 1 | 0.5600 | 236 − 148 = 88 | 49.2822 |
| 2 | 0.3315 | 195 − 154 = 41 | 13.5914 |
| 3 | 0.2260 | 182 − 158 = 24 | 5.4243 |
| 4 | 0.1433 | 170 − 160 = 10 | 1.4329 |
| 5 | 0.0698 | 166 − 161 = 5 | 0.3488 |
The products use the unrounded weights. Their sum is , and . For , line L7 gives , , , and . Line L8 gives , and . The test rejects normality at 1%. The value 236 is far from the others. Without it, and . With all eleven values on the log scale, and : the log removes part of the skewness, but not all.
Three values, exact. For , , , and . Line L6 gives . The smallest possible value for is , for two equal values and one different value, and there .
Correctness
Line L4 computes , because lets each pair be written as , and the middle term is 0 when is odd. Because and , is the squared correlation of and , so by the Cauchy-Schwarz inequality, and the minimum in line L5 only removes rounding above 1. does not change when every becomes with : for the order is kept, and for the order is reversed and the antisymmetry of changes only the sign of . So the null law of does not depend on and . is at least , with equality for equal values and one different value; the proof reduces this to an inequality on the coefficients, which was checked by computation for every from 3 to 5000. For the p-value in line L6 is the exact null distribution, so the size is exactly . This is proved.
Two things are only measured. The approximate coefficients are within of the exact ones for , computed from the order statistic integrals: for the exact upper half is , and the approximation gives . The p-value is an approximation: with 20000 seeded normal samples of each size (4000 for ), the size of the nominal 5% test was 0.0538 at , 0.0464 at , 0.0511 at , 0.0498 at , 0.0495 at and 0.0505 at . The correctness proof gives each step.
Proof: The Shapiro-Wilk statistic is a squared correlation in its proven range, it is invariant, and its p-value is exact for three observationsfull
We prove that SHAPIRO-WILK returns , that is the squared correlation of the sorted sample with the weights, that is location and scale invariant, that , and that for line L6 returns the exact p-value, so the test has size exactly . Two things are not proved, and the page reports them as measured: that Royston's weights in line L2 are close to the exact , and that the normalizing transform in lines L7 to L9 gives a p-value close to the true one for . The lower bound uses one inequality on the weights, which we check by computation and do not prove.
Throughout, is the output of line L2. By construction it satisfies , so and when is odd, and , because the middle weights are scaled by for exactly this. It is also increasing, . The middle weights are increasing because is increasing; that the end weights are larger than their neighbors is a property of the fitted polynomials, which the tests check for ten values of from 3 to 500, and Lemma 4 only uses the signs for .
Lemma 1 (line L4). .
Proof. Group the terms and for : , because . When is odd, the middle term is .
Lemma 2 (squared correlation and the upper bound). If , then , where is the sample correlation of and , and , with if and only if is a multiple of .
Proof. Since , and . So . By the Cauchy-Schwarz inequality, , with equality if and only if the two vectors are proportional.
So line L5 returns in exact arithmetic, and the minimum with 1 only removes rounding.
Lemma 3 (invariance). Let with . Then .
Proof. If , the sorted sample is . Then , because , and . If , the order reverses: , so . With , , so , and again . In both cases .
So under the law of is the same for every and , and the p-value may be computed for standard normal data.
Lemma 4 (lower bound). Let for . Assume
Then for every sample with , with equality for .
Proof. First, . If , every with is and is among them. If , , and every with is .
Write and for the vector with for and otherwise. Then . Since , . Let , the centered ; then and . By the triangle inequality, . Not all are 0 because , so
where the last step holds because a ratio of sums with nonnegative weights is at least the smallest ratio of the terms. By (C), for every . So .
For , and , so .
Condition (C) holds with equality for and , since and . For these are all the . For the weights of line L2, a computation over every from 3 to 5000 and every found the smallest value of to be , which is 1 up to rounding. So (C) holds for the weights used, as a checked computation and not as a proof for a general .
Lemma 5 (the exact law for ). If are iid , then for .
Proof. For , line L2 gives , so : half the squared range over . The centered vector is the orthogonal projection of onto the plane . Since , the projection has the law in each of two orthonormal coordinates of the plane, independently, so it is for an orthonormal basis of the plane, with uniform on and independent of . The projections of the three unit vectors onto the plane have length and are apart, so the three centered values are for , and .
So , where . The function has period , because adding to permutes the three values, and it is even about , because replaces each by its negative up to the same permutation. Hence is also even about , and the law of is the law of with uniform on . For , the largest of is and the smallest is , because . Their difference is , so .
Let , uniform on . For , if and only if or , a set of length in an interval of length . This gives the stated distribution function.
Lemma 6 (size for ). For the p-value of line L6 is uniform on under , and rejecting when has size exactly .
Proof. Line L6 returns , where is the distribution function of Lemma 5, clipped to only against rounding. is continuous and strictly increasing on and has this law, so is uniform, by the probability integral transform. Hence . Small gives small , as the test requires.
What is measured and not proved. For the weights of line L2 and the transform in lines L7 to L9 are Royston's fitted approximations. The tests compute the exact weights for from the integrals that define the means and covariances of normal order statistics and find the approximations within . Seeded simulations give a size of the nominal 5% test between 0.046 and 0.054 for from 4 to 200. Lemmas 1 to 4 hold for the weights of line L2 whatever their accuracy, because they use only the antisymmetry, the unit norm, the order and condition (C).
Termination. Line L1 sorts values. Line L2 makes calls of , each a fixed number of operations, and a fixed number of polynomial evaluations. Lines L3 to L5 are three passes over values. Lines L6 to L9 are a fixed number of operations and one call of . Every step is a bounded loop, so the algorithm stops.
Theorem. For and data that are not all equal, SHAPIRO-WILK returns , which is the squared correlation of the sorted sample with the weights, is invariant under with , and lies in . For the returned p-value is exact and the test has size exactly .
Proof. Lemmas 1 to 6, with condition (C) checked by computation for the weights used.
Complexity
On a real RAM with and as unit-cost operations, line L1 takes comparisons, line L2 evaluations of , and lines L3 to L9 more. The total is time and extra space for the sorted copy and the weights. Computing the exact weights instead would need numerical integrals and a solve. The original tables stop at , and all later algorithms use approximate weights.
Numerical stability. is computed in two passes, mean first, which avoids the cancellation of when the values are large and close together. When the implementation stops with an error, because is undefined. Rounding can make slightly larger than 1 for data that are exactly on a line, so line L5 clips it. Line L7 uses through log1p(-W), which keeps relative accuracy when is near 1, as it is for large normal samples. Line L9 computes the upper normal tail directly, so very small p-values do not round to 0. For the transform needs . The implementation returns otherwise, but this guard never acts on valid data: for , and for , would need , below the minimum .
Properties
- Invariant. does not change under with , so the test needs no estimate of or .
- Bounded. . The lower bound is for , for , for , for and for (with the weights of line L2). only when the sorted sample is exactly a linear function of .
- Exact for only. For the null density of is on . For larger both the weights and the p-value are approximations.
- Close to Shapiro-Francia. For large , is close to a multiple of , so is close to the squared correlation of the sorted sample with , which is the Shapiro-Francia statistic.
- Not distribution free. The null law of is for the normal family only. It cannot be used for another family without new weights and new tables.
Variants and improvements
- Shapiro-Francia W'. Shapiro and Francia (1972) replaced by itself, which avoids . Then is the squared correlation of a normal Q-Q plot. Royston's approximation of uses Blom's scores for the middle weights, so for large the two statistics are close.
- D'Agostino-Pearson . It combines the sample skewness and kurtosis, each with a normalizing transform. It tells which moment is wrong, but it has less power against some alternatives.
- Anderson-Darling and Lilliefors. The Anderson-Darling test and the Kolmogorov-Smirnov test compare the empirical distribution function with a normal one. With and estimated from the data, the plain tables are wrong, and the Lilliefors tables or a parametric bootstrap are needed. Anderson-Darling is close to Shapiro-Wilk in power; Kolmogorov-Smirnov has much less power.
- Algorithm AS 181. Royston (1982) gave the first algorithm for up to 2000. AS R94 (1995) replaced it with the approximations used here and extended the range to .
- Censored samples. Royston's AS R94 also handles samples where the largest values are censored, by using only the first order statistics.
- Residuals. Applied to the residuals of a linear model, for example the studentized residuals, the test is a common check of the normal error assumption. The null law is then only approximate, because residuals are not independent.
When to use it
Use the Shapiro-Wilk test when you need a formal check of normality for a sample of moderate size, from about 10 to a few thousand, for example before a procedure whose validity depends on normality in small samples. Always look at a Q-Q plot as well: it shows the kind and the size of the departure, which a p-value does not. For very large samples, judge the size of the departure from the plot and from the effect on the procedure you plan to use, not from the p-value. To test a fully specified distribution, or a family other than the normal, use the Kolmogorov-Smirnov test, the Anderson-Darling test or the chi-squared goodness of fit test.
Pitfalls
- "Not rejected" is not "normal". At the test rejects exponential data less than half the time, and uniform data less than one time in ten, as the power figures above show. A large p-value from a small sample says little.
- Large samples reject small departures. With thousands of values, a skewness too small to affect a t-test gives a tiny p-value.
- Testing before choosing the test. Choosing a t-test or a rank test from the result of a normality test on the same data changes the error rates of the second test.
- Ties and rounding. Data rounded to a coarse grid have many ties, which lower and can make the test reject normal data. Constant data have no at all.
- Out of range. The constants are fitted for . The implementation refuses other .
- Wrong tail. Small is evidence against normality. Values of near 1 are what normal data give.
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)
sw_core.py 92 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shapiro-wilk-test/. The authors are listed in prov/F6R58F.jsonl.
"""The Shapiro-Wilk W test of normality, with Royston's approximations.
W = (sum a_i y_(i))^2 / sum (y_i - ybar)^2, where y_(1) <= ... <= y_(n) is
the sorted sample and a is proportional to V^(-1) m, with m and V the mean
vector and covariance matrix of standard normal order statistics, scaled
so that sum a_i^2 = 1. The coefficients a and the p-value use the
approximations of Royston (1992), in the form of Algorithm AS R94 (Royston
1995): the coefficients from m_i = Phi^(-1)((i - 3/8)/(n + 1/4)) with a
polynomial correction of the two largest, and a normalizing transform of
W whose upper tail is the p-value. For n = 3 the p-value is exact. For
n >= 4 the coefficients are within about 1e-3 of the exact ones for small
n (measured) and the p-value is an approximation.
The code is in this file and not in shapiro_wilk_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_ppf, norm_sf
# Royston's polynomials, coefficients in increasing powers.
_C1 = (0.0, 0.221157, -0.147981, -2.07119, 4.434685, -2.706056) # a_n, in 1/sqrt(n)
_C2 = (0.0, 0.042981, -0.293762, -1.752461, 5.682633, -3.582633) # a_(n-1), in 1/sqrt(n)
_C3 = (0.544, -0.39978, 0.025054, -6.714e-4) # mean, n <= 11, in n
_C4 = (1.3822, -0.77857, 0.062767, -0.0020322) # log sd, n <= 11, in n
_C5 = (-1.5861, -0.31082, -0.083751, 0.0038915) # mean, n >= 12, in log n
_C6 = (-0.4803, -0.082676, 0.0030302) # log sd, n >= 12, in log n
def _poly(c: Sequence[float], x: float) -> float:
r = 0.0
for v in reversed(c):
r = r * x + v
return r
def shapiro_wilk_coefficients(n: int) -> list[float]:
"""Royston's approximation of a = V^(-1) m / ||V^(-1) m||, for 3 <= n <= 5000."""
if not 3 <= n <= 5000:
raise ValueError("need 3 <= n <= 5000")
if n == 3:
return [-math.sqrt(0.5), 0.0, math.sqrt(0.5)]
m = [norm_ppf((i - 0.375) / (n + 0.25)) for i in range(1, n + 1)]
mm = math.fsum(v * v for v in m)
u = 1.0 / math.sqrt(n)
a = [0.0] * n
an = _poly(_C1, u) + m[-1] / math.sqrt(mm)
if n > 5:
an1 = _poly(_C2, u) + m[-2] / math.sqrt(mm)
phi = (mm - 2 * m[-1] ** 2 - 2 * m[-2] ** 2) / (1 - 2 * an ** 2 - 2 * an1 ** 2)
a[0], a[1], a[-2], a[-1] = -an, -an1, an1, an
lo, hi = 2, n - 2
else:
phi = (mm - 2 * m[-1] ** 2) / (1 - 2 * an ** 2)
a[0], a[-1] = -an, an
lo, hi = 1, n - 1
for i in range(lo, hi):
a[i] = m[i] / math.sqrt(phi)
return a
def shapiro_wilk(x: Sequence[float]) -> tuple[float, float]:
"""Shapiro-Wilk test of normality; returns (W, p), with p small for non-normal data."""
n = len(x)
if not 3 <= n <= 5000:
raise ValueError("need 3 <= n <= 5000")
y = sorted(x) # @line L1
a = shapiro_wilk_coefficients(n) # @line L2
mean = math.fsum(y) / n # @line L3
ss = math.fsum((v - mean) ** 2 for v in y)
if ss == 0.0:
raise ValueError("all observations are equal")
b = math.fsum(a[n - 1 - i] * (y[n - 1 - i] - y[i]) for i in range(n // 2)) # @line L4
w = min(b * b / ss, 1.0) # @line L5
if n == 3: # @line L6
p = 6.0 / math.pi * (math.asin(math.sqrt(w)) - math.pi / 3.0)
return w, min(max(p, 0.0), 1.0)
w1 = math.log1p(-w) if w < 1.0 else -math.inf # @line L7
if n <= 11:
gamma = -2.273 + 0.459 * n
if w1 >= gamma: # W below the range of the transform: p is negligible
return w, 0.0
t = -math.log(gamma - w1)
mu, sd = _poly(_C3, n), math.exp(_poly(_C4, n))
else:
t = w1
mu, sd = _poly(_C5, math.log(n)), math.exp(_poly(_C6, math.log(n)))
z = (t - mu) / sd # @line L8
return w, norm_sf(z) # @line L9
shapiro_wilk_test.py 8 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shapiro-wilk-test/. The authors are listed in prov/F6R58F.jsonl.
"""Entry point named after the slug. The code lives in sw_core.py, because tools treat
a file whose name ends in _test.py as a test file and skip its @line markers."""
from sw_core import shapiro_wilk, shapiro_wilk_coefficients
__all__ = ["shapiro_wilk", "shapiro_wilk_coefficients"]
test_shapiro_wilk_test.py 157 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shapiro-wilk-test/. The authors are listed in prov/F6R58F.jsonl.
import math
import random
from statistics import NormalDist
import pytest
from shapiro_wilk_test import shapiro_wilk, shapiro_wilk_coefficients
_N = NormalDist()
def exact_coefficients(n: int, h: float = 0.01, half_width: float = 8.0):
"""Brute force: a = V^(-1) m / ||V^(-1) m|| from the order statistic integrals.
m_i = E Y_(i) and E Y_(i) Y_(j) for standard normal order statistics, by the
trapezoid rule on [-half_width, half_width]. The double integral for i < j
uses (F(v) - F(u))^d = sum_t C(d, t) F(v)^t (-F(u))^(d - t) and suffix sums.
"""
xs = [-half_width + h * k for k in range(int(round(2 * half_width / h)) + 1)]
K = len(xs)
f = [_N.pdf(v) for v in xs]
F = [_N.cdf(v) for v in xs]
w = [h] * K
w[0] = w[-1] = h / 2
lg = math.lgamma
def single(i: int, power: int) -> float:
c = math.exp(lg(n + 1) - lg(i) - lg(n - i + 1))
return sum(w[k] * xs[k] ** power * c * F[k] ** (i - 1) * (1 - F[k]) ** (n - i) * f[k]
for k in range(K))
m = [single(i, 1) for i in range(1, n + 1)]
e2 = [[0.0] * n for _ in range(n)]
for i in range(1, n + 1):
e2[i - 1][i - 1] = single(i, 2)
for i in range(1, n + 1):
for j in range(i + 1, n + 1):
d = j - i - 1
c = math.exp(lg(n + 1) - lg(i) - lg(d + 1) - lg(n - j + 1))
total = 0.0
for t in range(d + 1):
g = [xs[k] * F[k] ** t * (1 - F[k]) ** (n - j) * f[k] for k in range(K)]
suffix, acc = [0.0] * K, 0.0 # suffix[k] = trapezoid integral of g on [x_k, end]
for k in range(K - 1, -1, -1):
if k < K - 1:
acc += 0.5 * h * (g[k] + g[k + 1])
suffix[k] = acc
total += math.comb(d, t) * sum(
w[k] * xs[k] * F[k] ** (i - 1) * f[k] * (-F[k]) ** (d - t) * suffix[k]
for k in range(K))
e2[i - 1][j - 1] = e2[j - 1][i - 1] = c * total
v = [[e2[i][j] - m[i] * m[j] for j in range(n)] for i in range(n)]
aug = [row[:] + [m[i]] for i, row in enumerate(v)]
for col in range(n):
piv = max(range(col, n), key=lambda r: abs(aug[r][col]))
aug[col], aug[piv] = aug[piv], aug[col]
for r in range(n):
if r != col:
fac = aug[r][col] / aug[col][col]
aug[r] = [a - fac * b for a, b in zip(aug[r], aug[col])]
y = [aug[i][n] / aug[i][i] for i in range(n)]
norm = math.sqrt(sum(t * t for t in y))
return v, [t / norm for t in y]
def direct_w(x: list[float], a: list[float]) -> float:
"""Brute force: W as the squared correlation of the sorted sample with a."""
y = sorted(x)
n = len(y)
ya, aa = sum(y) / n, sum(a) / n
sxy = sum((p - ya) * (q - aa) for p, q in zip(y, a))
sxx = sum((p - ya) ** 2 for p in y)
syy = sum((q - aa) ** 2 for q in a)
return sxy * sxy / (sxx * syy)
def test_worked_example() -> None:
x = [148, 154, 158, 160, 161, 162, 166, 170, 182, 195, 236]
w, p = shapiro_wilk(x)
assert w == pytest.approx(0.78881, abs=1e-5)
assert p == pytest.approx(0.006704, abs=2e-6)
assert shapiro_wilk(x[:-1])[0] == pytest.approx(0.9080, abs=1e-4)
def test_coefficients_against_exact_order_statistic_integrals() -> None:
for n in (4, 5, 6):
v, exact = exact_coefficients(n)
for row in v: # for normal order statistics each row of V sums to 1
assert sum(row) == pytest.approx(1.0, abs=1e-5)
approx = shapiro_wilk_coefficients(n)
assert max(abs(p - q) for p, q in zip(approx, exact)) < 1.5e-3
def test_coefficient_properties() -> None:
for n in (3, 4, 5, 6, 7, 11, 12, 30, 101, 500):
a = shapiro_wilk_coefficients(n)
assert sum(t * t for t in a) == pytest.approx(1.0, abs=1e-12)
assert all(a[i] == pytest.approx(-a[n - 1 - i], abs=1e-15) for i in range(n))
assert all(a[i] < a[i + 1] for i in range(n - 1))
def test_w_against_direct_correlation_formula() -> None:
rng = random.Random(41)
for _ in range(50):
n = rng.randint(3, 60)
x = [rng.gauss(0.0, 1.0) if rng.random() < 0.5 else rng.expovariate(1.0) for _ in range(n)]
w, p = shapiro_wilk(x)
assert w == pytest.approx(direct_w(x, shapiro_wilk_coefficients(n)), rel=1e-12)
assert 0.0 <= p <= 1.0
def test_location_scale_invariance_and_bounds() -> None:
rng = random.Random(42)
for _ in range(40):
n = rng.randint(3, 40)
x = [rng.gauss(5.0, 2.0) for _ in range(n)]
w, p = shapiro_wilk(x)
w2, p2 = shapiro_wilk([3.0 - 7.5 * t for t in x])
assert w2 == pytest.approx(w, rel=1e-12) and p2 == pytest.approx(p, rel=1e-9, abs=1e-15)
an = shapiro_wilk_coefficients(n)[-1]
assert n * an * an / (n - 1) - 1e-12 <= w <= 1.0
# The bound is attained by n - 1 equal values and one different value.
assert shapiro_wilk([0.0] * (n - 1) + [1.0])[0] == pytest.approx(n * an * an / (n - 1), rel=1e-12)
def test_n3_null_distribution_is_exact() -> None:
assert shapiro_wilk([0.0, 0.0, 1.0])[0] == pytest.approx(0.75)
assert shapiro_wilk([0.0, 0.0, 1.0])[1] == pytest.approx(0.0, abs=1e-12)
assert shapiro_wilk([0.0, 1.0, 2.0]) == pytest.approx((1.0, 1.0))
rng = random.Random(43)
ps = [shapiro_wilk([rng.gauss(0.0, 1.0) for _ in range(3)])[1] for _ in range(20000)]
for u in (0.05, 0.1, 0.5, 0.9):
assert abs(sum(p <= u for p in ps) / len(ps) - u) < 0.012
def test_monte_carlo_size_and_power() -> None:
rng = random.Random(44)
reps = 1500
for n in (10, 30):
size = sum(shapiro_wilk([rng.gauss(0.0, 1.0) for _ in range(n)])[1] <= 0.05
for _ in range(reps)) / reps
assert abs(size - 0.05) < 0.02
power = sum(shapiro_wilk([rng.expovariate(1.0) for _ in range(30)])[1] <= 0.05
for _ in range(300)) / 300
assert power > 0.8
def test_rejects_bad_input() -> None:
with pytest.raises(ValueError):
shapiro_wilk([1.0, 2.0])
with pytest.raises(ValueError):
shapiro_wilk([4.0, 4.0, 4.0, 4.0])
with pytest.raises(ValueError):
shapiro_wilk_coefficients(5001)
History
Samuel Shapiro and Martin Wilk published the test in Biometrika in 1965. They called it an analysis of variance test, because compares a generalized least squares estimate of from the ordered sample with the usual estimate. They gave the weights and the percentage points of for up to 50, and the exact null distribution for . Because the weights for larger needed the covariances of normal order statistics, Shapiro and Francia (1972) proposed the simpler . Patrick Royston extended the test to with Algorithm AS 181 in 1982, gave new approximations of the weights and a normalizing transform in 1992, and published Algorithm AS R94 in 1995 with the range . AS R94 is the algorithm behind the Shapiro-Wilk functions in most statistical software.
References
- S. S. Shapiro and M. B. Wilk, An analysis of variance test for normality (complete samples), Biometrika 52(3-4) (1965), pages 591 to 611, the definition of W, its invariance and its range, and the exact null distribution for n = 3
- Patrick Royston, Approximating the Shapiro-Wilk W-test for non-normality, Statistics and Computing 2(3) (1992), pages 117 to 119, the polynomial approximations of the coefficients and the normalizing transform of W
- Patrick Royston, Remark AS R94, A remark on algorithm AS 181, the W-test for normality, Journal of the Royal Statistical Society Series C (Applied Statistics) 44(4) (1995), pages 547 to 551, the algorithm with the constants used here, for 3 <= n <= 5000
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 F6R58F Edit this page History Report an error Markdown