jeudi 20 mai 2021

How to simulate First passage time probability in python for a Random Walk?

I have a 2D random walk where the particle have equal probabilities to move to the left, right, up, down or stay in the same position (I generate a random number from to 1 to 5 to decide in which direction the particle will move). The particle will perform n steps, and i repeat the simulation several times.

I want to plot the probability F(t) of hitting a trap located in x=-10 for the first time (the particle will disappear after hitting this point). I started counting the number of particles fp for each simulation that hit the trap, adding the value 1 each time i have a particle in the position x=-10. After this i ploted fp, number of particles hitting the trap for the fisrt time, vs t- the time steps.

import matplotlib.pyplot as plt 
import matplotlib
import numpy as np
import pylab
import random

n = 1000

n_simulations=1000
x = numpy.zeros((n_simulations,n))
y = numpy.zeros((n_simulations,n))
steps = np.arange(0, n, 1)
for i in range (n_simulations):
    for j in range (1,n):
        val=random.randint(1,5)
        if val == 1:
            x[i,j] = x[i,j - 1] + 1
            y[i,j] = y[i,j - 1] 
        elif val == 2:
            x[i,j] = x[i,j - 1] - 1
            y[i,j] = y[i,j - 1] 
        elif val == 3:
            x[i,j] = x[i,j - 1]
            y[i,j] = y[i,j - 1] + 1
        elif val == 4:
            x[i,j] = x[i,j - 1]
            y[i,j] = y[i,j - 1] - 1
        else:
            x[i,j] = x[i,j - 1]
            y[i,j] = y[i,j - 1]
        if x[i,j] == -10:
            break
fp = numpy.zeros((n_simulations,n)) # number of paricles that hit the trap for each simulation. 
for i in range(n_simulations):
    for j in range (1,n):
        if x[i,j] == -10:
            fp[i,j] = fp[i,j-1] +1
        else:
            fp[i,j] = fp[i,j-1]
s=  [sum(x) for x in zip(*fp)]        
plt.xlim(0,1000)
plt.plot(steps,s)
plt.show()

I should have the folowing plot: Probability of hitting the target as a function of time

But the plot i get is diferent since the curve is always increasing and it should decrease for large t (for large t, most particles hitted the target and the probability decreases) . Even without using the sum of fp i don't have the desired result. I would like to know where my code is wrong:This is the plot i get with my code




Aucun commentaire:

Enregistrer un commentaire