#Source this code to run it # Random walk code. p is .5 by default rwalk=function(n,p=.5) { # Reset the graphics window #dev.off() #windows() par(mfrow =c(2,1)) # Change Bernoulli outcomes to +1 or -1 outcomes X = 2*rbinom(n,1,p)-1 S = cumsum(X) # Study behavior of the cumulative sum ts.plot(X,xlab="Step",ylab="Winnings",ylim=c(-2,2)) abline(h=0,col="red") title("Individual Steps") ts.plot(S,xlab="Step",ylab="Total Winnings") title("Random Walk") abline(v=which(S==0),h=0,col="red") # Some useful statistics Smax=max(S) Sfin=S[n] SReturn=sum(S==0) out <- list(X,S,Sfin,Smax,SReturn) names(out) <- c("Outcomes","Random Walk","Final Winnings","Maximum Winnings","Returns") out }