# In a random walk simulation, how do I get the mean and standard deviation of how many times the walk returns to the origin?

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')


#####################################################################

UPDATED CODE:

#####################################################################

def Move( N ) :
x = 0 # starting from origin position
i = 0 # count
steps = [] # history of all positions after each step
for i in range(N) :
step = StepsFunc()
x += step
steps.append(x)
return steps

N = 1000
walks = 1000

StepsList=[]

for i in range(walks):
StepsList.append(Move( N ))

ZerosList = []
for x in StepsList:
temp = 0
for y in x:
if y == 0:
temp += 1
ZerosList.append(temp)


I was able to use this to then calculate the mean and standard deviation.

• CAN YOU PLEASE PROVIDE US THE CHANGED CODE? THANKS IN ADVANCE
– user38211
May 12, 2021 at 13:26
• @Tsiantakis yeah, sure. I've added it. May 14, 2021 at 12:17
• thanks mate nice and clear code.Understandable
– user38211
May 14, 2021 at 14:16

At the moment, you aren't tracking the number of times a walk reaches zero or even if a walk reaches zero at any point. Your Move function returns the last position of the walk, so you are only checking whether the 1000th step is zero. You should change Move to store the count of how many times that walk reaches zero. You can then determine the mean and standard deviation of the number of times a walk returns to zero.