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: