模拟随机漫步

随机漫步是每次步行方向和步长都是随机的,没有明确的方向(当然代码里是有四个方向的,上下左右),结果由一系列随机决策决定的。本实例中random_walk.py决策步行的左右上下方向和步长的随机性,rw_visual.py是图形化展示。本例是在Unbuntu19.10中实现的。

 

random_walk.py,源码如下:

 1 from random import choice
 2 '''一个随机生成漫步数据的类'''
 3 
 4 class RandomWalk():
 5     '''初始化随机漫步数据'''
 6     def __init__(self,num_points = 5000):
 7         self.num_points = num_points
 8 
 9         '''所有漫步都从(0,0)开始'''
10         self.x_values = [0]
11         self.y_values = [0]
12 
13     def get_steps_x(self):
14         '''获取沿x轴随机走了多远的类'''
15         #决定沿x轴前进的方向以及沿该方向走了多远距离
16         self.x_direction = choice([1,-1]) #1为向右,x轴的正方向;-1为向左,x轴的反方向;
17         self.x_distance = choice([0,1,2,3,4])
18         self.x_steps = self.x_direction * self.x_distance
19         return self.x_steps
20 
21     def get_steps_y(self):
22         '''获取沿y轴随机走了多远的类'''
23         #决定沿y轴前进的方向以及沿该方向走了多远的类
24         self.y_direction = choice([1,-1])
25         self.y_distance = choice([0,1,2,3,4])
26         self.y_steps = self.y_direction * self.y_distance
27         return self.y_steps
28 
29     def fill_walk(self):
30         '''类方法,计算漫步包含的所有的点'''
31 
32         #不断漫步,直到达到列表指定长度
33         while len(self.x_values) < self.num_points:
34             #获取沿x轴走了多少步
35             self.get_steps_x()
36 
37             #获取沿y轴走了多少步
38             self.get_steps_y()
39 
40             #不可以原地不动
41             if self.x_steps == 0 and self.y_steps == 0:
42                 continue
43 
44             #计算下一个点的x和y值
45             next_x = self.x_values[-1] + self.x_steps
46             next_y = self.y_values[-1] + self.y_steps
47 
48             #将获取到的x值和y值加入到列表末尾
49             self.x_values.append(next_x)
50             self.y_values.append(next_y)
51             

rw_visual.py,源码如下:

 1 import matplotlib.pyplot as plt
 2 
 3 from random_walk import RandomWalk
 4 
 5 #只要程序处于活动状态,就一直模拟随机漫步
 6 
 7 while True:
 8     #创建一个RandomWalk实例,并将其包含的所有点绘制出来
 9     rw = RandomWalk()
10     rw.fill_walk()
11 
12     #绘制起点,并以绿色显示
13     plt.scatter(0,0,c='green',edgecolor='none',s=200)
14 
15     #开始随机漫步,并给点着色
16     point_number = list(range(rw.num_points))
17     plt.scatter(rw.x_values,rw.y_values,c=point_number,cmap=plt.cm.Blues,edgecolor='none',s=10)
18 
19     #绘制终点,并以红色显示
20     plt.scatter(rw.x_values[-1],rw.y_values[-1],c='red',edgecolor='none',s=200)
21 
22     #设置标题和x轴标题和y轴标题
23     plt.title("Random Walk",fontsize=24)
24     plt.xlabel("X values",fontsize=14)
25     plt.ylabel("Y steps",fontsize=14)
26     plt.tick_params(axis='both',labelsize=14)
27 
28     #隐藏坐标轴
29     plt.axes().get_xaxis().set_visible(False)
30     plt.axes().get_yaxis().set_visible(False)
31 
32     #以图片形势显示随机漫步的结果
33     plt.show()
34 
35     keep_running = input("Make another walk? (y/n): ")
36     if keep_running == 'n':
37         break

 

posted @ 2020-05-18 16:27  、一叶孤城  阅读(195)  评论(0)    收藏  举报