In a 1-d random walk simulation, how to get the mean and standard deviation of how many times the walk returns to the origin

computational mathematicspythonrandom walksimulation

So I'm simulating a 1-dimensional random walk, with 1000 walks that each take 1000 steps.

How do I calculate the average number of times that a walker returns to the origin and then the standard deviation of the number of times that a walker returns to the origin?

I feel like I'm not understanding the logic of how to manipulate this to get the answers I need, so if anyone could help, that'd be really helpful! The code I have for now is:

def StepsFunc() :
    step = np.random.randint( 2 )

    #step is 0 or 1, want -1 or +1
    if step == 0 :
        step = -1
    return step

#defining another function, which will actually take N number of steps
def Move( N ) : 
    x = 0 # starting from origin position
    i = 0 # count
  
    while i <= N-1 :
        step = StepsFunc()
        x += step
        i += 1
    return x

#number of steps
N = 1000

#number of random walks
walks = 1000

StepsList=[]

num=0
for i in range(walks):
    x = Move( N )
    if x == 0:
        num += 1    
    StepsList.append( x )
    

print("The random walk returns to zero {} times".format(num))
print(np.mean(StepsList)) #average of all walks
print(num/walks) #getting the average number of walks that returned to zero?
#plt.hist(StepsList, bins='auto')

Best Answer

I think this one does what you're looking for:

import numpy

Nstep = 1000
Nsim = 1000

step_cases = [1,-1]
p = [0.5,0.5]

steps = numpy.random.choice(a=step_cases,size=(Nsim,Nstep),p=p)

sim = numpy.zeros((Nsim,Nstep))
for k in range(1,Nstep):
    sim[:,k]=sim[:,k-1]+steps[:,k]

zeros_sim = numpy.zeros(Nsim)
for k in range(0,Nsim):
    zeros_sim[k] = numpy.sum(numpy.where(sim[k,:]==0,1,0))-1 # do not count the start
    
print(numpy.average(zeros_sim))
print(numpy.std(zeros_sim))
Related Question