# Control Chart: Nelson alternating rule

The Nelson rules for control charts describe patterns, which are "special" and need our attention. One of these rules is the "alternation rule". According to Nelson it is "unusual" to obtain a series of 14 alternating points -- direction does not matter.

I tried to simulate the probability of such an event using a normal distribution. Here my code:

nSim  = 1e6
count = 0
n     = 14
iVec1 = seq(1, n, by=2)
iVec2 = iVec1 + 1
for (i in 1:nSim){
tmp     = rnorm(n)
sumSide = sum( tmp[iVec1] > tmp[iVec2] )
if ( sumSide >= round(n/2) ){
count = count + 1
} else if ( sumSide == 0 ){
count = count + 1
}
}
print(100*count/nSim)


which yields a probability close to 1.5%. However, the analytic result yields a probability around 0.45%, which is approx. a factor three off. Is this an artefact of the non-true randomness of the used random numbers?

The problem is not with R's PRNG, but with the logic used to conduct Nelson's fourth test.

Consider the simple case tmp <- 1:14:

count = 0
n     = 14
iVec1 = seq(1, n, by=2)
iVec2 = iVec1 + 1
tmp   = 1:n
sum(tmp[iVec1] > tmp[iVec2])
#>  0


This would have incorrectly incremented count in the OP's script. Instead we can do:

nSim <- 1e7L
n <- 14L
sum(colSums(abs(diff(sign(diff(matrix(rnorm(n*nSim), n)))))) == 2L*(n - 2L))/nSim
#>  0.0045829


Which is consistent with the known analytical result of $$\frac{398721962}{14!}\approx0.00457$$