Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterative
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 a1,…,ana_1, \dots, a_n, which come from the means and covariances of the order statistics of a standard normal sample. The statistic WW is the squared correlation between the sorted sample and the weights. It is at most 1, and small values are evidence against normality. WW itself is computed exactly. The p-value comes from a normalizing transform by Royston, which is an approximation for every n≥4n \ge 4; for n=3n = 3 the null distribution of WW 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 x1,…,xnx_1, \dots, x_n are iid from a continuous distribution FF, with 3≤n≤50003 \le n \le 5000. The null hypothesis is that FF is normal with some mean μ\mu and some variance σ2>0\sigma^2 > 0, both unknown. The alternative is every other FF. It is a composite null, and the test is omnibus: it does not target one kind of departure.

Statistic. Let y1≤⋯≤yny_1 \le \dots \le y_n be the sorted sample. Let m=(m1,…,mn)m = (m_1, \dots, m_n) be the expected values of the order statistics of nn iid standard normal variables, and VV their covariance matrix. The weights are

a=V−1m∥V−1m∥,W=(∑i=1naiyi)2∑i=1n(yi−yˉ)2.a = \frac{V^{-1}m}{\lVert V^{-1}m \rVert}, \qquad W = \frac{\left(\sum_{i=1}^n a_i y_i\right)^2}{\sum_{i=1}^n (y_i - \bar y)^2}.

The weights are antisymmetric, ai=−an+1−ia_i = -a_{n+1-i}, so ∑iai=0\sum_i a_i = 0, and ∑iai2=1\sum_i a_i^2 = 1. Thus WW is the squared correlation between (yi)(y_i) and (ai)(a_i). The vector V−1mV^{-1}m is proportional to the coefficients of the generalized least squares estimate of σ\sigma from the ordered sample, so the numerator is a constant times the square of that estimate, and the denominator is (n−1)(n - 1) times the sample variance.

Null distribution. WW is location and scale invariant, so under H0H_0 its law depends on nn only. For n=3n = 3 it is exact: P(W≤w)=6π(arcsin⁡w−π3)P(W \le w) = \frac6\pi\left(\arcsin\sqrt w - \frac\pi3\right) for 34≤w≤1\frac34 \le w \le 1. For n≥4n \ge 4 there is no closed form. Royston fitted a transform t(W)t(W) whose null law is close to normal, with mean μn\mu_n and standard deviation σn\sigma_n given as polynomials in nn or in log⁡n\log n. This is an empirical fit to simulated values. It is not a theorem.

Rejection rule and size. Reject at level α\alpha when p≤αp \le \alpha, that is when WW is small. For n=3n = 3 the size is exactly α\alpha. For n≥4n \ge 4 the size is close to α\alpha but not exactly α\alpha. The Monte Carlo sizes below are measured, not proved.

p-value. p=PH0(W≤Wobs)p = P_{H_0}(W \le W_{\text{obs}}), a lower tail of WW, which is the upper tail of the normal approximation of t(W)t(W): p≈1−Φ((t(W)−μn)/σn)p \approx 1 - \Phi\left((t(W) - \mu_n)/\sigma_n\right).

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 n=3,5,10,20,50n = 3, 5, 10, 20, 50, and against uniform data it was 0.06, 0.06, 0.07, 0.21 and 0.75. With small nn the test cannot see much. With very large nn it rejects for departures from normality too small to matter.

The algorithm

  1. SHAPIRO-WILK(x₁, …, xₙ) ▷ 3 ≤ n ≤ 5000, not all equal
  2. 1y ← x sorted in increasing order
  3. 2a ← Royston coefficients for n ▷ antisymmetric, Σaᵢ² = 1; exact ±√½ for n = 3
  4. 3ȳ ← Σ yᵢ / n; SS ← Σ (yᵢ − ȳ)²
  5. 4b ← Σ_{i=1}^{⌊n/2⌋} a_{n+1−i} (y_{n+1−i} − yᵢ) ▷ equals Σ aᵢ yᵢ
  6. 5W ← min(b²/SS, 1)
  7. 6if n = 3 then return (W, (6/π)(arcsin √W − π/3)) ▷ exact
  8. 7if n ≤ 11 then
  9. γ ← −2.273 + 0.459 n
  10. if log(1 − W) ≥ γ then return (W, 0)
  11. t ← −log(γ − log(1 − W)); μ, σ ← polynomials in n
  12. else
  13. t ← log(1 − W); μ, σ ← polynomials in log n
  14. 8z ← (t − μ)/σ
  15. 9return (W, 1 − Φ(z))

The coefficients (line L2). The exact aa needs the n×nn \times n 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 m~i=Φ−1((i−3/8)/(n+1/4))\tilde m_i = \Phi^{-1}\left((i - 3/8)/(n + 1/4)\right) in place of mim_i. With u=1/nu = 1/\sqrt n and ∥m~∥2=∑im~i2\lVert\tilde m\rVert^2 = \sum_i \tilde m_i^2,

an=m~n∥m~∥+0.221157u−0.147981u2−2.071190u3+4.434685u4−2.706056u5,a_n = \frac{\tilde m_n}{\lVert\tilde m\rVert} + 0.221157u - 0.147981u^2 - 2.071190u^3 + 4.434685u^4 - 2.706056u^5,

and for n≥6n \ge 6 also an−1a_{n-1} by a second polynomial with constants 0.042981,−0.293762,−1.752461,5.682633,−3.5826330.042981, -0.293762, -1.752461, 5.682633, -3.582633. The middle weights are ai=m~i/ϕa_i = \tilde m_i/\sqrt\phi, with ϕ\phi chosen so that ∑iai2=1\sum_i a_i^2 = 1, and the lower half is the mirror image. The mean and log standard deviation of tt are

μn=0.544−0.39978n+0.025054n2−0.0006714n3,log⁡σn=1.3822−0.77857n+0.062767n2−0.0020322n3\mu_n = 0.544 - 0.39978n + 0.025054n^2 - 0.0006714n^3, \quad \log\sigma_n = 1.3822 - 0.77857n + 0.062767n^2 - 0.0020322n^3

for 4≤n≤114 \le n \le 11, and, with v=log⁡nv = \log n,

μn=−1.5861−0.31082v−0.083751v2+0.0038915v3,log⁡σn=−0.4803−0.082676v+0.0030302v2\mu_n = -1.5861 - 0.31082v - 0.083751v^2 + 0.0038915v^3, \quad \log\sigma_n = -0.4803 - 0.082676v + 0.0030302v^2

for n≥12n \ge 12.

Example

Eleven measurements. Take x=148,154,158,160,161,162,166,170,182,195,236x = 148, 154, 158, 160, 161, 162, 166, 170, 182, 195, 236, already sorted. Then yˉ=172\bar y = 172 and SS=6226SS = 6226. Line L4 pairs the largest value with the smallest, the second largest with the second smallest, and so on:

ii a12−ia_{12-i} y12−i−yiy_{12-i} - y_i 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 b=70.0797b = 70.0797, and W=70.07972/6226=0.78881W = 70.0797^2/6226 = 0.78881. For n=11n = 11, line L7 gives γ=2.776\gamma = 2.776, log⁡(1−W)=−1.55502\log(1 - W) = -1.55502, t=−log⁡(2.776+1.55502)=−1.46580t = -\log(2.776 + 1.55502) = -1.46580, μn=−1.71568\mu_n = -1.71568 and σn=0.10105\sigma_n = 0.10105. Line L8 gives z=2.4728z = 2.4728, and p=0.006704p = 0.006704. The test rejects normality at 1%. The value 236 is far from the others. Without it, W=0.9080W = 0.9080 and p=0.268p = 0.268. With all eleven values on the log scale, W=0.8362W = 0.8362 and p=0.028p = 0.028: the log removes part of the skewness, but not all.

Three values, exact. For x=1,2,4x = 1, 2, 4, a=(−1/2,0,1/2)a = (-\sqrt{1/2}, 0, \sqrt{1/2}), b=3/2b = 3/\sqrt2, SS=14/3SS = 14/3 and W=4.5/(14/3)=27/28=0.96429W = 4.5/(14/3) = 27/28 = 0.96429. Line L6 gives p=6π(arcsin⁡27/28−π3)=0.6369p = \frac6\pi\left(\arcsin\sqrt{27/28} - \frac\pi3\right) = 0.6369. The smallest possible value for n=3n = 3 is W=3/4W = 3/4, for two equal values and one different value, and there p=0p = 0.

Correctness

Line L4 computes ∑iaiyi\sum_i a_i y_i, because ai=−an+1−ia_i = -a_{n+1-i} lets each pair be written as an+1−i(yn+1−i−yi)a_{n+1-i}(y_{n+1-i} - y_i), and the middle term is 0 when nn is odd. Because ∑iai=0\sum_i a_i = 0 and ∑iai2=1\sum_i a_i^2 = 1, b2/SSb^2/SS is the squared correlation of yy and aa, so W≤1W \le 1 by the Cauchy-Schwarz inequality, and the minimum in line L5 only removes rounding above 1. WW does not change when every xix_i becomes c+dxic + dx_i with d≠0d \ne 0: for d>0d > 0 the order is kept, and for d<0d < 0 the order is reversed and the antisymmetry of aa changes only the sign of bb. So the null law of WW does not depend on μ\mu and σ\sigma. WW is at least nan2/(n−1)na_n^2/(n - 1), with equality for n−1n - 1 equal values and one different value; the proof reduces this to an inequality on the coefficients, which was checked by computation for every nn from 3 to 5000. For n=3n = 3 the p-value in line L6 is the exact null distribution, so the size is exactly α\alpha. This is proved.

Two things are only measured. The approximate coefficients are within 1.5×10−31.5 \times 10^{-3} of the exact ones for n=4,5,6n = 4, 5, 6, computed from the order statistic integrals: for n=6n = 6 the exact upper half is 0.6431,0.2806,0.08760.6431, 0.2806, 0.0876, and the approximation gives 0.6430,0.2807,0.08830.6430, 0.2807, 0.0883. The p-value is an approximation: with 20000 seeded normal samples of each size (4000 for n=200n = 200), the size of the nominal 5% test was 0.0538 at n=4n = 4, 0.0464 at n=5n = 5, 0.0511 at n=10n = 10, 0.0498 at n=20n = 20, 0.0495 at n=50n = 50 and 0.0505 at n=200n = 200. 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 W=(∑iaiyi)2/∑i(yi−yˉ)2W = (\sum_i a_iy_i)^2/\sum_i(y_i - \bar y)^2, that WW is the squared correlation of the sorted sample with the weights, that WW is location and scale invariant, that nan2/(n−1)≤W≤1na_n^2/(n - 1) \le W \le 1, and that for n=3n = 3 line L6 returns the exact p-value, so the test has size exactly α\alpha. Two things are not proved, and the page reports them as measured: that Royston's weights in line L2 are close to the exact V−1m/∥V−1m∥V^{-1}m/\lVert V^{-1}m\rVert, and that the normalizing transform in lines L7 to L9 gives a p-value close to the true one for n≥4n \ge 4. The lower bound uses one inequality on the weights, which we check by computation and do not prove.

Throughout, a=(a1,…,an)a = (a_1, \dots, a_n) is the output of line L2. By construction it satisfies ai=−an+1−ia_i = -a_{n+1-i}, so ∑iai=0\sum_i a_i = 0 and a(n+1)/2=0a_{(n+1)/2} = 0 when nn is odd, and ∑iai2=1\sum_i a_i^2 = 1, because the middle weights are scaled by ϕ\phi for exactly this. It is also increasing, a1<a2<⋯<ana_1 < a_2 < \dots < a_n. The middle weights are increasing because Φ−1\Phi^{-1} 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 nn from 3 to 500, and Lemma 4 only uses the signs ai<0a_i < 0 for i≤n/2i \le n/2.

Lemma 1 (line L4). b=∑i=1naiyib = \sum_{i=1}^n a_iy_i.

Proof. Group the terms ii and n+1−in + 1 - i for i≤⌊n/2⌋i \le \lfloor n/2\rfloor: aiyi+an+1−iyn+1−i=an+1−i(yn+1−i−yi)a_iy_i + a_{n+1-i}y_{n+1-i} = a_{n+1-i}(y_{n+1-i} - y_i), because ai=−an+1−ia_i = -a_{n+1-i}. When nn is odd, the middle term is a(n+1)/2y(n+1)/2=0a_{(n+1)/2}y_{(n+1)/2} = 0. □\square

Lemma 2 (squared correlation and the upper bound). If SS>0SS > 0, then b2/SS=r2b^2/SS = r^2, where rr is the sample correlation of (yi)(y_i) and (ai)(a_i), and 0≤b2/SS≤10 \le b^2/SS \le 1, with b2/SS=1b^2/SS = 1 if and only if y−yˉ1y - \bar y\mathbf 1 is a multiple of aa.

Proof. Since ∑iai=0\sum_i a_i = 0, ∑iai(yi−yˉ)=∑iaiyi=b\sum_i a_i(y_i - \bar y) = \sum_i a_iy_i = b and ∑i(ai−aˉ)2=∑iai2=1\sum_i (a_i - \bar a)^2 = \sum_i a_i^2 = 1. So r2=b2/(1⋅SS)r^2 = b^2/(1 \cdot SS). By the Cauchy-Schwarz inequality, b2=(∑iai(yi−yˉ))2≤∑iai2∑i(yi−yˉ)2=SSb^2 = \left(\sum_i a_i(y_i - \bar y)\right)^2 \le \sum_i a_i^2 \sum_i (y_i - \bar y)^2 = SS, with equality if and only if the two vectors are proportional. □\square

So line L5 returns b2/SSb^2/SS in exact arithmetic, and the minimum with 1 only removes rounding.

Lemma 3 (invariance). Let xi′=c+dxix_i' = c + dx_i with d≠0d \ne 0. Then W(x′)=W(x)W(x') = W(x).

Proof. If d>0d > 0, the sorted sample is yi′=c+dyiy_i' = c + dy_i. Then b′=∑iai(c+dyi)=dbb' = \sum_i a_i(c + dy_i) = db, because ∑iai=0\sum_i a_i = 0, and SS′=d2SSSS' = d^2SS. If d<0d < 0, the order reverses: yi′=c+dyn+1−iy_i' = c + dy_{n+1-i}, so b′=∑iai(c+dyn+1−i)=d∑iaiyn+1−ib' = \sum_i a_i(c + dy_{n+1-i}) = d\sum_i a_iy_{n+1-i}. With j=n+1−ij = n + 1 - i, ∑iaiyn+1−i=∑jan+1−jyj=−∑jajyj=−b\sum_i a_iy_{n+1-i} = \sum_j a_{n+1-j}y_j = -\sum_j a_jy_j = -b, so b′=−dbb' = -db, and again b′2=d2b2b'^2 = d^2b^2. In both cases W′=d2b2/(d2SS)=WW' = d^2b^2/(d^2SS) = W. □\square

So under H0H_0 the law of WW is the same for every μ\mu and σ>0\sigma > 0, and the p-value may be computed for standard normal data.

Lemma 4 (lower bound). Let ck=∑i>kaic_k = \sum_{i > k} a_i for 1≤k≤n−11 \le k \le n - 1. Assume

(n−1)ck2≥k(n−k)an2for 1≤k≤n−1.(C)(n - 1)c_k^2 \ge k(n - k)a_n^2 \quad \text{for } 1 \le k \le n - 1. \tag{C}

Then W≥nan2/(n−1)W \ge na_n^2/(n - 1) for every sample with SS>0SS > 0, with equality for y=(0,…,0,1)y = (0, \dots, 0, 1).

Proof. First, ck>0c_k > 0. If k≥n/2k \ge n/2, every aia_i with i>ki > k is ≥0\ge 0 and an>0a_n > 0 is among them. If k<n/2k < n/2, ck=−∑i≤kaic_k = -\sum_{i \le k} a_i, and every aia_i with i≤ki \le k is <0< 0.

Write dk=yk+1−yk≥0d_k = y_{k+1} - y_k \ge 0 and sks_k for the vector with sk,i=1s_{k,i} = 1 for i>ki > k and 00 otherwise. Then y=y11+∑k=1n−1dksky = y_1\mathbf 1 + \sum_{k=1}^{n-1} d_ks_k. Since a⊤1=0a^\top\mathbf 1 = 0, b=∑kdkckb = \sum_k d_kc_k. Let tk=sk−n−kn1t_k = s_k - \frac{n - k}{n}\mathbf 1, the centered sks_k; then y−yˉ1=∑kdktky - \bar y\mathbf 1 = \sum_k d_kt_k and ∥tk∥2=(n−k)−(n−k)2/n=k(n−k)/n\lVert t_k\rVert^2 = (n - k) - (n - k)^2/n = k(n - k)/n. By the triangle inequality, SS≤∑kdk∥tk∥\sqrt{SS} \le \sum_k d_k\lVert t_k\rVert. Not all dkd_k are 0 because SS>0SS > 0, so

W=∑kdkckSS≥∑kdkck∑kdk∥tk∥≥min⁡kck∥tk∥,\sqrt W = \frac{\sum_k d_kc_k}{\sqrt{SS}} \ge \frac{\sum_k d_kc_k}{\sum_k d_k\lVert t_k\rVert} \ge \min_k \frac{c_k}{\lVert t_k\rVert},

where the last step holds because a ratio of sums with nonnegative weights is at least the smallest ratio of the terms. By (C), ck2/∥tk∥2=nck2/(k(n−k))≥nan2/(n−1)c_k^2/\lVert t_k\rVert^2 = nc_k^2/(k(n - k)) \ge na_n^2/(n - 1) for every kk. So W≥nan2/(n−1)W \ge na_n^2/(n - 1).

For y=(0,…,0,1)y = (0, \dots, 0, 1), b=anb = a_n and SS=1−1/n=(n−1)/nSS = 1 - 1/n = (n - 1)/n, so W=nan2/(n−1)W = na_n^2/(n - 1). □\square

Condition (C) holds with equality for k=1k = 1 and k=n−1k = n - 1, since c1=−a1=anc_1 = -a_1 = a_n and cn−1=anc_{n-1} = a_n. For n=3n = 3 these are all the kk. For the weights of line L2, a computation over every nn from 3 to 5000 and every kk found the smallest value of (n−1)ck2/(k(n−k)an2)(n - 1)c_k^2/(k(n - k)a_n^2) to be 1−4×10−131 - 4 \times 10^{-13}, 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 nn.

Lemma 5 (the exact law for n=3n = 3). If x1,x2,x3x_1, x_2, x_3 are iid N(μ,σ2)N(\mu, \sigma^2), then P(W≤w)=6π(arcsin⁡w−π3)P(W \le w) = \frac6\pi\left(\arcsin\sqrt w - \frac\pi3\right) for 34≤w≤1\frac34 \le w \le 1.

Proof. For n=3n = 3, line L2 gives a=(−1/2,0,1/2)a = (-1/\sqrt2, 0, 1/\sqrt2), so W=(y3−y1)2/(2SS)W = (y_3 - y_1)^2/(2SS): half the squared range over SSSS. The centered vector x−xˉ1x - \bar x\mathbf 1 is the orthogonal projection of xx onto the plane 1⊥\mathbf 1^\perp. Since x∼N(μ1,σ2I)x \sim N(\mu\mathbf 1, \sigma^2I), the projection has the law N(0,σ2)N(0, \sigma^2) in each of two orthonormal coordinates of the plane, independently, so it is R(cos⁡Θ e+sin⁡Θ f)R(\cos\Theta\,e + \sin\Theta\,f) for an orthonormal basis e,fe, f of the plane, with Θ\Theta uniform on [0,2π)[0, 2\pi) and independent of RR. The projections of the three unit vectors onto the plane have length 2/3\sqrt{2/3} and are 2π/32\pi/3 apart, so the three centered values are 2/3 Rcos⁡(Θ−φj)\sqrt{2/3}\,R\cos(\Theta - \varphi_j) for φj=φ1+2π(j−1)/3\varphi_j = \varphi_1 + 2\pi(j - 1)/3, and SS=R2SS = R^2.

So W=g(Θ)W = g(\Theta), where g(θ)=13(max⁡jcos⁡(θ−φj)−min⁡jcos⁡(θ−φj))2g(\theta) = \frac13\left(\max_j\cos(\theta - \varphi_j) - \min_j\cos(\theta - \varphi_j)\right)^2. The function gg has period 2π/32\pi/3, because adding 2π/32\pi/3 to θ\theta permutes the three values, and it is even about φ1\varphi_1, because θ↦2φ1−θ\theta \mapsto 2\varphi_1 - \theta replaces each θ−φj\theta - \varphi_j by its negative up to the same permutation. Hence gg is also even about φ1+π/3\varphi_1 + \pi/3, and the law of g(Θ)g(\Theta) is the law of g(φ1+U)g(\varphi_1 + U) with UU uniform on [0,π/3][0, \pi/3]. For 0≤u≤π/30 \le u \le \pi/3, the largest of cos⁡u,cos⁡(u−2π/3),cos⁡(u+2π/3)\cos u, \cos(u - 2\pi/3), \cos(u + 2\pi/3) is cos⁡u\cos u and the smallest is cos⁡(u+2π/3)\cos(u + 2\pi/3), because u+2π/3∈[2π/3,π]u + 2\pi/3 \in [2\pi/3, \pi]. Their difference is 2sin⁡(u+π/3)sin⁡(π/3)=3sin⁡(u+π/3)2\sin(u + \pi/3)\sin(\pi/3) = \sqrt3\sin(u + \pi/3), so g(φ1+u)=sin⁡2(u+π/3)g(\varphi_1 + u) = \sin^2(u + \pi/3).

Let v=U+π/3v = U + \pi/3, uniform on [π/3,2π/3][\pi/3, 2\pi/3]. For 34≤w≤1\frac34 \le w \le 1, sin⁡2v≤w\sin^2 v \le w if and only if v≤arcsin⁡wv \le \arcsin\sqrt w or v≥π−arcsin⁡wv \ge \pi - \arcsin\sqrt w, a set of length 2(arcsin⁡w−π/3)2(\arcsin\sqrt w - \pi/3) in an interval of length π/3\pi/3. This gives the stated distribution function. □\square

Lemma 6 (size for n=3n = 3). For n=3n = 3 the p-value of line L6 is uniform on [0,1][0, 1] under H0H_0, and rejecting when p≤αp \le \alpha has size exactly α\alpha.

Proof. Line L6 returns G(W)G(W), where GG is the distribution function of Lemma 5, clipped to [0,1][0, 1] only against rounding. GG is continuous and strictly increasing on [34,1][\frac34, 1] and WW has this law, so G(W)G(W) is uniform, by the probability integral transform. Hence P(G(W)≤α)=αP(G(W) \le \alpha) = \alpha. Small WW gives small pp, as the test requires. □\square

What is measured and not proved. For n≥4n \ge 4 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 n=4,5,6n = 4, 5, 6 from the integrals that define the means and covariances of normal order statistics and find the approximations within 1.5×10−31.5 \times 10^{-3}. Seeded simulations give a size of the nominal 5% test between 0.046 and 0.054 for nn 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 nn values. Line L2 makes nn calls of Φ−1\Phi^{-1}, each a fixed number of operations, and a fixed number of polynomial evaluations. Lines L3 to L5 are three passes over nn values. Lines L6 to L9 are a fixed number of operations and one call of Φ\Phi. Every step is a bounded loop, so the algorithm stops.

Theorem. For 3≤n≤50003 \le n \le 5000 and data that are not all equal, SHAPIRO-WILK returns W=(∑iaiyi)2/SSW = (\sum_i a_iy_i)^2/SS, which is the squared correlation of the sorted sample with the weights, is invariant under x↦c+dxx \mapsto c + dx with d≠0d \ne 0, and lies in [nan2/(n−1),1][na_n^2/(n - 1), 1]. For n=3n = 3 the returned p-value is exact and the test has size exactly α\alpha.

Proof. Lemmas 1 to 6, with condition (C) checked by computation for the weights used. ■\blacksquare

Complexity

On a real RAM with Φ−1\Phi^{-1} and Φ\Phi as unit-cost operations, line L1 takes Θ(nlog⁡n)\Theta(n\log n) comparisons, line L2 Θ(n)\Theta(n) evaluations of Φ−1\Phi^{-1}, and lines L3 to L9 Θ(n)\Theta(n) more. The total is Θ(nlog⁡n)\Theta(n\log n) time and Θ(n)\Theta(n) extra space for the sorted copy and the weights. Computing the exact weights V−1mV^{-1}m instead would need Θ(n2)\Theta(n^2) numerical integrals and a Θ(n3)\Theta(n^3) solve. The original tables stop at n=50n = 50, and all later algorithms use approximate weights.

Numerical stability. SSSS is computed in two passes, mean first, which avoids the cancellation of ∑yi2−nyˉ2\sum y_i^2 - n\bar y^2 when the values are large and close together. When SS=0SS = 0 the implementation stops with an error, because WW is undefined. Rounding can make b2/SSb^2/SS slightly larger than 1 for data that are exactly on a line, so line L5 clips it. Line L7 uses log⁡(1−W)\log(1 - W) through log1p(-W), which keeps relative accuracy when WW 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 n≤11n \le 11 the transform needs log⁡(1−W)<γ\log(1 - W) < \gamma. The implementation returns p=0p = 0 otherwise, but this guard never acts on valid data: γ≥0.022\gamma \ge 0.022 for 5≤n≤115 \le n \le 11, and for n=4n = 4, γ=−0.437\gamma = -0.437 would need W≤0.354W \le 0.354, below the minimum 0.62980.6298.

Properties

  • Invariant. WW does not change under x↦c+dxx \mapsto c + dx with d≠0d \ne 0, so the test needs no estimate of μ\mu or σ\sigma.
  • Bounded. nan2/(n−1)≤W≤1na_n^2/(n - 1) \le W \le 1. The lower bound is 0.750.75 for n=3n = 3, 0.62980.6298 for n=4n = 4, 0.55220.5522 for n=5n = 5, 0.49610.4961 for n=6n = 6 and 0.36570.3657 for n=10n = 10 (with the weights of line L2). W=1W = 1 only when the sorted sample is exactly a linear function of aa.
  • Exact for n=3n = 3 only. For n=3n = 3 the null density of WW is 3π(w(1−w))−1/2\frac3\pi\left(w(1 - w)\right)^{-1/2} on [34,1][\frac34, 1]. For larger nn both the weights and the p-value are approximations.
  • Close to Shapiro-Francia. For large nn, V−1mV^{-1}m is close to a multiple of mm, so WW is close to the squared correlation of the sorted sample with mm, which is the Shapiro-Francia statistic.
  • Not distribution free. The null law of WW 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 V−1mV^{-1}m by mm itself, which avoids VV. Then W′W' is the squared correlation of a normal Q-Q plot. Royston's approximation of WW uses Blom's scores for the middle weights, so for large nn the two statistics are close.
  • D'Agostino-Pearson K2K^2. 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 μ\mu and σ\sigma 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 nn up to 2000. AS R94 (1995) replaced it with the approximations used here and extended the range to 3≤n≤50003 \le n \le 5000.
  • Censored samples. Royston's AS R94 also handles samples where the largest values are censored, by using only the first n1n_1 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 n=10n = 10 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 WW and can make the test reject normal data. Constant data have no WW at all.
  • Out of range. The constants are fitted for 3≤n≤50003 \le n \le 5000. The implementation refuses other nn.
  • Wrong tail. Small WW is evidence against normality. Values of WW 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.

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)
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 WW compares a generalized least squares estimate of σ2\sigma^2 from the ordered sample with the usual estimate. They gave the weights and the percentage points of WW for nn up to 50, and the exact null distribution for n=3n = 3. Because the weights for larger nn needed the covariances of normal order statistics, Shapiro and Francia (1972) proposed the simpler W′W'. Patrick Royston extended the test to n=2000n = 2000 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 3≤n≤50003 \le n \le 5000. AS R94 is the algorithm behind the Shapiro-Wilk functions in most statistical software.

References

  1. 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
  2. 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
  3. 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.

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