Math & Physics Problems Wikia
Advertisement
Math & Physics Problems Wikia

By: Tao Steven Zheng (郑涛)

 1 import numpy as np
 2 import matplotlib.pyplot as plt
 3 
 4  def Randwalk(n):
 5  
 6     x = 0
 7     y = 0
 8  
 9     time = [x]
10     position = [y] 
11  
12     for i in range (1,n+1):
13         move = np.random.uniform(0,1)
14  
15         if move < 0.5:    
16             x += 1
17             y += 1  
18  
19         if move > 0.5:    
20             x += 1
21             y += -1
22   
23         time.append(x)
24         position.append(y)
25  
26     return [time,position]
27 
28 
29 '''Trials and plots'''
30  Randwalk1 = Randwalk(1000)
31  Randwalk2 = Randwalk(1000)
32  Randwalk3 = Randwalk(1000)
33  plt.plot(Randwalk1[0],Randwalk1[1],'r-', label = "Randwalk1")
34  plt.plot(Randwalk2[0],Randwalk2[1],'g-', label = "Randwalk2")
35  plt.plot(Randwalk3[0],Randwalk3[1],'b-', label = "Randwalk3")
36  plt.title("1-D Random Walks")
37  plt.legend(loc='upper center', bbox_to_anchor=(0.5,-0.1), fancybox=True, shadow=True)
38  plt.show()


1d random walk.png
Advertisement