I am trying to solve this problem where we have a 1D-lattice of size 100 and the particle can start from any position in the lattice and moves randomly on it(with equal probability of moving to either direction). When the particle reaches either of the ends of the lattice it stops. The problem is to plot the time average(to reach the boundary) vs initial starting position of the particle when for each starting position we take 10000 trails to compute the time average.
This is my code
for i in range(1,size):
timearr=[]
for j in range(trails):
time=0
x=i
while True:
r = random.randint(-1,1)
time+=1
x+=r
if x==0 or x==size:
timearr.append(time)
break
timemean.append(np.mean(timearr))
xarr= np.arange(1,size)
plt.plot(xarr, timemean)
plt.show()
However, taking size as 100 and trials as 10000(or even 1000) it takes a humongous amount of time to run this. Is there any way to solve this faster using Python. Ideally, I would like to do this using a vectorised approach using numpy arrays. But I can't think of how to implement control-flow in that case.
numpy
and vectorization. However, I would expect marginal improvement for this algorithm. $\endgroup$