Hey fellas:

In the context of the gambler's ruin problem, the following R code obtains the mean duration of the game, in turns:

# total.capital is a constant, an arbitrary positive integer
# initial.capital is a constant, an arbitrary positive integer between, and not including
# 0 and total.capital
# p is the probability of winning 1$ on each turn
# 1-p is the probability of loosing 1$
# N is a large integer representing the number of times to simulate
# dur is a vector containing the simulated game durations


T <- total.capital
dur <- NULL
for (n in 1:N) {
    x <- initial.capital
    d <- 0
    while ((x!=0)&(x!=T)) {
       x <- x+sample(c(-1,1),1,replace=TRUE,c(1-p,p))
       d <- d+1
    }
   dur <- c(dur,d)
}
mean(dur) #returns the mean duration of the game

The problem with this code is that, using the traditional control structures (while, for, etc.) it is rather slow. Does anyone know of a way i could vectorize the "while" and the "for" to produce a faster code?

And while I'm at it, does anyone know of a discrete-event simulation package in R such as the "SimPy" for Python?


Thanks in advance


	[[alternative HTML version deleted]]

