随机漫步生成是无规则的,是系统自行选择的结果。根据设定的规则自定生成,上下左右的方位,每次所经过的方向路径。
首先,创建一个randomwalk()类和fill_walk()函数
random_walk.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
from random import choice class randomwalk (): '''一个生成随机数漫步的类''' def __init__( self ,num_point = 5000 ): '''初始化随机漫步的属性''' self .num_point = num_point #所有随机漫步的开始都是坐标[0,0] self .x_lab = [ 0 ] self .y_lab = [ 0 ] def fill_walk( self ): '''计算随机漫步的所有点''' while len ( self .x_lab) < self .num_point: #决定前进方向以及前进的距离 x_direction = choice([ 1 , - 1 ]) x_distance = choice([ 0 , 1 , 2 , 3 , 4 ]) x_step = x_direction * x_distance y_direction = choice([ 1 , - 1 ]) y_distance = choice([ 0 , 1 , 2 , 3 , 4 ]) y_step = y_direction * y_distance #拒绝原地不动 if x_step = = 0 and y_step = = 0 : continue #计算下一个点x和y的值 next_x = self .x_lab[ - 1 ] + x_step next_y = self .y_lab[ - 1 ] + y_step self .x_lab.append(next_x) self .y_lab.append(next_y) |
2、绘制随机漫步图
rw_visual.py
1
2
3
4
5
6
7
|
import matplotlib.pyplot as plt from random_walk import randomwalk from random import choice rw = randomwalk() rw.fill_walk() plt.scatter(rw.x_lab,rw.y_lab,s = 15 ) plt.show() |
3、生成效果图片
4、修改代码-->隐藏边框
rw_visual.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
import matplotlib.pyplot as plt from random_walk import randomwalk from random import choice while true: rw = randomwalk() rw.fill_walk() #设置绘画窗口大小 plt.figure(dpi = 128 ,figsize = ( 10 , 6 )) point_numbers = list ( range (rw.num_point)) #突出起点(0,0)和终点 plt.scatter( 0 , 0 ,c = 'green' ,edgecolors = 'none' ,s = 100 ) plt.scatter(rw.x_lab[ - 1 ],rw.y_lab[ - 1 ],c = 'red' ,edgecolors = 'none' ,s = 100 ) #隐藏坐标轴 plt.axes().get_xaxis().set_visible(false) plt.axes().get_yaxis().set_visible(false) plt.scatter(rw.x_lab,rw.y_lab,c = point_numbers,cmap = plt.cm.blues,edgecolors = 'none' ,s = 15 ) plt.show() keep_running = input ( "make another walk?(y/n): " ) keep_running = keep_running.lower() if keep_running = = 'n' : break |
5、展示效果
总结
以上所述是小编给大家介绍的python实现随机漫步功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!
原文链接:https://www.cnblogs.com/JeremyWYL/archive/2018/07/09/8652110.html