Finding the mean time to reach a given threshold for random walk in python

354 Views Asked by At

I have a code for a random walk of 10000 steps. I then had to repeat the simulation 12 times and save each in a separate text file, which I have done. I have now been given a task, to find on average, how many steps it takes for the random walk to reach x = 10, when it starts from (0,0). This means if you imagine there is a North South line at x = 10, I need to calculate the mean for my 12 walks, for how many steps it takes to reach x = 10 from starting position (0,0). I think it would involve using an if statement but I'm not sure how to use that in my code and how to get my code to tell me how many steps it took to get there for each run, and then calculate the mean for all the runs.

My code for the random walk and saving different runs in separate text files is as follows:


import numpy as np 
import matplotlib.pyplot as plt
import random as rd
import math

a = (np.zeros((10000, 2), dtype=np.float)) 
     
def randwalk(x,y):
     theta= 2*math.pi*rd.random()
     x+=math.cos(theta); 
     y+=math.sin(theta); 
     return (x,y)
     
x, y = 0.,0.  
for i in range(10000): 
     x, y = randwalk(x,y)
     a[i,:] = x,y
     
plt.figure() 
plt.title("10000 steps 2D Random Walk")
plt.plot(a[:,0],a[:,1], color = 'y')
plt.show()

N = 12
for j in range(N): 
    rd.seed(j) 
    x , y = 0., 0.
    for i in range(10000):
        x, y = randwalk(x,y)
        a[i,:] = x, y
    filename = 'Walk'+ str(j) 
    np.savetxt(filename, a) 

1

There are 1 best solutions below

2
On

The short answer:

np.argmax(np.abs(a[:, 0]) > 10)

What this does:

  1. np.abs(a[:, 0]) is the absolute value of the x values
  2. * > 10 is an array that's True whenever the above is greater than 10
  3. np.argmax(*) gives the argument of the maximum value in *. since it's boolean the max is True (1). argmax always gives the first instance of max so it's the first True

Thus this gives the index of the first step above 10, which is equivalent to how long it took to reach |x| > 10.

Now, the reason I used the absolute value is that a walk is not guaranteed to get to 10 (or -10, but both is much less likely), so you'll have some corner cases to cover if you only want 10.