import random
import matplotlib.pyplot as plt
class random_walks:
def __init__(self,n=100,step_length=0.1):
self.x=[0]
self.y=[0]
self.x2=[0]
self.n=n
self.l=step_length
def walk(self):
for i in range(1,self.n):
self.x.append(i)
temp=random.random()
if temp < 0.5:
self.y.append(self.y[-1]+self.l)
elif temp > 0.5:
self.y.append(self.y[-1]-self.l)
def show(self):
plt.plot(self.x,self.y,'o')
plt.title('random walk in one dimension')
plt.xlabel('step number')
plt.ylabel('x')
plt.grid(True)
a=random_walks()
a.walk()
a.show()
b=random_walks()
b.walk()
b.show()
网友评论