项目 数据可视化4 随机漫步

 1 from random import choice
 2 class RandomWalk():
 3 
 4     def __init__(self, num_points=5000):
 5 
 6         self.num_points = num_points
 7 
 8         self.x_values = [0]
 9         self.y_values = [0]
10 
11     def fill_walk(self):
12         while len(self.x_values) < self.num_points:
13             x_direction = choice([1,-1])
14             x_distance = choice([0,1,2,3,4])
15             x_step = x_direction*x_distance
16 
17             y_direction = choice([1,-1])
18             y_distance = choice([0,1,2,3,4])
19             y_step = y_direction*y_distance
20 
21             if x_step ==0 and y_step == 0:
22                 continue 
23 
24             next_x = self.x_values[-1]+x_step
25             next_y = self.y_values[-1]+y_step
26 
27             self.x_values.append(next_x)
28             self.y_values.append(next_y)
1 import matplotlib.pyplot as plt
2 from random_walk import RandomWalk
3 rw = RandomWalk()
4 rw.fill_walk()
5 plt.scatter(rw.x_values,rw.y_values,s=15)
6 plt.show()

猜你喜欢

转载自www.cnblogs.com/zhulvbo/p/8922769.html