Advertisement
Guest User

Random walk probability: return to origin

a guest
May 4th, 2012
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 0.77 KB | None | 0 0
  1. random.walk <- function(n){
  2.   steps <- rbinom(n, 1,0.5)*2-1
  3.   pos <-0  
  4.   k<-n
  5.   pos.hx <- seq(from=0, to=0, length.out=n)
  6.   for (i in 1:n){
  7.     pos <- steps[i]+pos
  8.     pos.hx[i] <- pos    
  9.     if (pos==0){k<-i
  10.       return(k)
  11.     }
  12.   }
  13.   return(k)
  14. }
  15.  
  16. simulations <- function(n, lim=100000){
  17.   termination <- seq(from=0, to=0, length.out=n)
  18.   for (i in 1:n){
  19.     termination[i]<-random.walk(lim)
  20.   }
  21.   no.return <- sum(termination==lim)    
  22.   avg.walk<-mean(termination[termination<lim])
  23.   return(c(no.return, avg.walk))
  24. }
  25.  
  26. # Two input params: number of simulations, and max number of coin flips
  27. # two output values: total number of simulations that did not return to origin,
  28. #   and avg number of flips/steps taken to return
  29. simulations(10000, lim=100000)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement