def walk(): 'starting at x=0, step left/right with probability 1/2 until x=1' x=0 while x!=1: x+=random.choice([-1,1]) # equi-probable left-right move yield x from __future__ import division # want floating point division fig,ax=subplots() p = linspace(0,0.5,20) ax.plot(p,p/(1-p),label=r'$p<1/2$',lw=3.) ax.plot([0.5,1],[1,1],label=r'$p > 1/2$',lw=3.) ax.axis(ymax=1.1) ax.legend(loc=0) ax.set_xlabel('$p$',fontsize=16) ax.set_ylabel('$P$',fontsize=16) ax.set_title(r'Probability of reaching $x=1$ from $x=0$',fontsize=16) ax.grid() def walk(): 'starting at x=0, step left/right with probability 1/2 until x=1' x=0 while x!=1: x+=random.choice([-1,1]) # equi-probable left-right move yield x random.seed(123) # set seed for reproducibility s = list(walk()) # generate the random steps fig,ax=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 = [list(walk()) for i in range(50)] # generate 50 random walks len_walk=map(len,s) # lengths of each walk fig,ax=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'%(mean(len_walk))) def walk(limit=50): 'limited version of random walker' x=0 while x!=1 and abs(x)