In [45]:
from numpy import random
import matplotlib.pyplot as plt
%matplotlib inline

def walk():
     x=0
     while x !=1 :
         x+=random.choice([-1,1]) 
         yield x
In [56]:
random.seed(288) #  set seed for reproducibility
s = list(walk()) # generate the random steps
fig,ax=plt.subplots()
ax.plot(s)
ax.set_ylabel("particle's x-position",fontsize=16)
ax.set_xlabel('step index k',fontsize=16)
ax.set_title('Example of random walk',fontsize=16)
s
Out[56]:
[-1, 0, -1, 0, -1, 0, 1]
In [57]:
import numpy as np
random.seed(123) 
s = [list(walk()) for i in range(50)] # generate 50 random walks
len_walk=list(map(len,s)) # lengths of each walk


fig,ax=plt.subplots()
for i in s:
    ax.plot(i)
ax.set_ylabel("particle's x-position",fontsize=16)
ax.set_xlabel('step index k',fontsize=16)
ax.set_title('average length=%3.2f'%(np.mean(len_walk)))
Out[57]:
Text(0.5,1,'average length=20.36')
In [ ]:
 
In [ ]: