Question 2, Page 194
Use the linear congruence method to generate
linear congruence formula is as follow where a is the multiplier, b is the increment and c is the remainder An example from the textbook (A First Course in Mathematical Modeling, page 193), if \(x_n = 115\) then $x_{n+1} $= remainder (122/10) = 2
$ x_{n+1} = ( a * x_n + b) mod (c) $
library(knitr)
library(animation)
library(plot3D)
#install.ImageMagick()
lcg.rand <- function(n=10, a, b,c) {
rng <- vector(length = n)
a <- a # mulitplier
b <- b #increment
c <- c #modulus
# Set the seed using the current system time in microseconds
d <- as.numeric(Sys.time()) * 1000
for (i in 1:n) {
d <- (a * d + b) %% c
rng[i] <- d / c
}
return(rng)
}
lcg.rand(10,5,1,8)
## [1] 0.2037354 0.1436768 0.8433838 0.3419189 0.8345947 0.2979736 0.6148682
## [8] 0.1993408 0.1217041 0.7335205
n <- c(10,15,20, 100, 500, 1000, 3000, 5000, 10000, 20000)
saveGIF({
for (i in 1:length(n)) {
x <- lcg.rand(n[i],5,1,8)
y <- lcg.rand(n[i],5,1,8)
z <- lcg.rand(n[i],5,1,8)
scatter3D(x, y, z, colvar = NULL, pch=20, cex = 0.5, theta=20, main = paste('n = ', n[i]))
}
}, movie.name = 'lcg.gif')
## Executing:
## "convert -loop 0 -delay 100 Rplot1.png Rplot2.png Rplot3.png
## Rplot4.png Rplot5.png Rplot6.png Rplot7.png Rplot8.png
## Rplot9.png Rplot10.png "lcg.gif""
## Output at: lcg.gif
## [1] TRUE
Different Sample Size of Random Number
saveGIF({
for (i in 1:length(n)) {
x <- lcg.rand(n[i],1,7,10)
y <- lcg.rand(n[i],1,7,10)
z <- lcg.rand(n[i],1,7,10)
scatter3D(x, y, z, colvar = NULL, pch=20, cex = 0.5, theta=20, main = paste('n = ', n[i]))
}
}, movie.name = 'lcg2.gif')
## Executing:
## "convert -loop 0 -delay 100 Rplot1.png Rplot2.png Rplot3.png
## Rplot4.png Rplot5.png Rplot6.png Rplot7.png Rplot8.png
## Rplot9.png Rplot10.png "lcg2.gif""
## Output at: lcg2.gif
## [1] TRUE
B. Radom numbers by Different Parameters
saveGIF({
for (i in 1:length(n)) {
x <- lcg.rand(n[i],5,3,16)
y <- lcg.rand(n[i],5,3,16)
z <- lcg.rand(n[i],5,3,16)
scatter3D(x, y, z, colvar = NULL, pch=20, cex = 0.5, theta=20, main = paste('n = ', n[i]))
}
}, movie.name = 'lcg3.gif')
## Executing:
## "convert -loop 0 -delay 100 Rplot1.png Rplot2.png Rplot3.png
## Rplot4.png Rplot5.png Rplot6.png Rplot7.png Rplot8.png
## Rplot9.png Rplot10.png "lcg3.gif""
## Output at: lcg3.gif
## [1] TRUE
C. Radom numbers by Different Parameters
Reference https://rpubs.com/aaronsc32/linear-congruential-generator-r