n <- 100000 # Number of Steps in RW sims <- 20 # Number of Random Walks simulated # Initialise some values i<-0 x <- seq(3,n,1) S <- matrix(0,n,sims) clt <- matrix(0,n,sims) lil <- matrix(0,n,sims) lln <- matrix(0,n,sims) # Generate Data - comment out S for different random variables for(k in 1:sims){ # Sum of Bernoulli random variables S[,k] <- cumsum(sample(c(-1, 1), n, TRUE)) # change values in c to change rw values # Sum of Normal Random Variables # S[,k] <- cumsum(rnorm(n,mean=0,sd=1)) for (i in 3:n){ clt[i,k] <- clt[i,k] + S[i,k]/sqrt(i) lil[i,k] <- lil[i,k] + S[i,k]/sqrt(i*log(log(i))) lln[i,k] <- lln[i,k] + S[i,k]/i i <- i+1 } } # Generate Plots # Random Walk Plot plot(S[,1], main="Random Walk", typ='l',ylab="",xlab="n",ylim=c(-1.3*sqrt(2*n*log(log(n))),1.3*sqrt(2*n*log(log(n)))), xlim=c(1,n),log="x") for (k in 2:sims){ Sys.sleep(0.5) lines(S[,k],typ='l',col=k) } lines(x,sqrt(2*x*log(log(x))), typ='l',lty=2, col="red") lines(x,-sqrt(2*x*log(log(x))), typ='l',lty=2, col="red") # LLN Plot plot(lln[,1], main="Law of Large Numbers", typ='l', ylab="", xlab="n", ylim=c(-1.2,1.2), xlim=c(5,n), log="x") lines(x,sqrt((2*log(log(x)))/x),typ='l',lty=2, col="red") lines(x,-sqrt((2*log(log(x)))/x),typ='l',lty=2, col="red") for (k in 2:sims){ Sys.sleep(0.5) lines(lln[,k],typ='l',col=k) } # CLT Plot plot(clt[,1], main="Central Limit Theorem", typ='l',xlab="n", ylab="", ylim=c(-4,4),xlim=c(5,n), log="x") abline(h=2.326348, lty=2, col="red") abline(h=-2.326348, lty=2, col="red") for (k in 2:sims){ Sys.sleep(0.5) lines(clt[,k],typ='l',col=k) } # LIL Plot plot(lil[,1], main="Law of Iterated Logarithm", typ='l',xlab="n", ylab="", ylim=c(-4,4), xlim=c(5,n), log="x") abline(h=sqrt(2), lty=2, col="red") abline(h=-sqrt(2), lty=2, col="red") for (k in 2:sims){ Sys.sleep(0.5) lines(lil[,k],typ='l',col=k) }