随机漫步:每次行走完全是随机的,最没有明确的方向下,结果是由一系列随机决策产生的,如:蚂蚁在晕头转向的情况下,每次都沿随机方向前行,我们将模拟这一现象。
from random import choice
class RandomWalk():
'''一个生成随机漫步数据的类'''
def __init__(self,num_points=5000):
""""初始化随机漫步的属性"""
self.num_points=num_points
#所有随机漫步都始于(0,0)
self.x_values=[0]
self.y_values=[0]
def fill_walk(self):
'''计算随机漫步包含的所有点'''
#不断漫步,知道列表达式到指定的长度
while len(self.x_values) < self.num_points:
x_direction = choice([1,-1])
x_distance = choice([0,1,2,3,4])
x_step = x_distance * x_direction
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_values[-1]+x_step
next_y = self.y_values[-1]+y_step
self.x_values.append(next_x)
self.y_values.append(next_y)
import matplotlib.pyplot as plt
#from random_walk import RandomWalk
#只要程序处于活动状态,就不断的模拟随机漫步
while True:
# 创建一个RandomWalk实例,并将其包含的点都绘制出来
rw=RandomWalk(50000)
rw.fill_walk()
#设置绘图窗口的尺寸
plt.figure(dpi=128,figsize=(10,6))
point_numbers = list(range(rw.num_points))
#以y值进行渐变
plt.scatter(rw.x_values,rw.y_values,c=point_numbers,cmap=plt.cm.Blues,edgecolors='none',s=1)
#突出起点和终点
#绿色起点
plt.scatter(rw.x_values[0],rw.y_values[0],c='green',edgecolors='none',s=100)
#红色终点
plt.scatter(rw.x_values[-1],rw.y_values[-1],c='Red',edgecolors='none',s=100)
#隐藏坐标轴
#plt.axes().get_xaxis().set_visible(False)
#plt.axes().get_yaxis().set_visible(False)
#获取当前的坐标轴,
# 设置x坐标轴为下边框
plt.gca().xaxis.set_ticks_position('top')
# 设置y坐标轴为左边框
plt.gca().yaxis.set_ticks_position('right')
# 设置x轴, y周在(0, 0)的位置
#plt.gca().spines['bottom'].set_position(('data', 0))
#plt.gca().spines['left'].set_position(('data', 0))
plt.show()
keep_running = input("Make another walk?(y/n): ")
if keep_running == 'n':
break
多执行几次,每次显示的图形都不一样,是不是有点艺术家的感觉了呢。