Simulation of a sequence of random numbers via modulo method

In [31]:
a <- 3
m <- 5987
seed <- 1

simulation <- seed
for (i in 1:(10e5-1)) {
    previous <- simulation[length(simulation)]
    simulation <- c(simulation, (a * previous) %% m)
}
In [33]:
plot(simulation[1:500], type='o')
In [34]:
length(unique(simulation))
2993
In [35]:
plot(table(simulation), xlim=c(1,100))
In [42]:
acf(simulation, lag.max=6000)
In [48]:
plot(simulation[1:100], simulation[51:150])
abline(lm(simulation[51:150] ~ simulation[1:100]), col='red')
cor(simulation[1:100], simulation[51:150])
-0.155170634261143
In [52]:
prefab <- read.csv('prefabricatedRandomNumbers.csv', as.is=T)[,1]
In [53]:
acf(prefab)

Gemischer linearer Kongruenzgenerator

In [69]:
b <- 3
c <- 5
k <- 10
a <- 4*c +1
m <- 2**k

seed <- 1

simulation <- seed
for (i in 1:(1e5-1)) {
    previous <- simulation[length(simulation)]
    simulation <- c(simulation, (a * previous + b) %% m)
}

acf(simulation)

Periodenlänge = m:

In [68]:
N <- length(simulation)
min(simulation[1:(N-m)] == simulation[(m+1):N])
1

Inversionsmethode für diskrete Zufallsvariablen

In [88]:
X <- c(1, 3, 5, 7)
p <- c(0.2, 0.1, 0.3, 0.4)

u <- runif(1)
for (i in 1:4) {
    if (u < sum(p[1:i])) break
}
print(u)
print(i)
print(X[i])
[1] 0.07267311
[1] 1
[1] 1