随机漫步
1.random_walk.py: 随机漫步,获得x,y的值
from random import choice
class RandomWalk:
def __init__(self, num_points=20000):
self.num_points = num_points
# x,y 初始坐标(0,0)
self.x_values = [0]
self.y_values = [0]
def get_step(self):
# 不断漫步,直到列表达到指定的长度
# 生成随机选择x,y方向
direction = choice([1, -1])
# 生成随机移动距离
distance = choice([0, 1, 2, 3, 4])
# 计算移动的距离
step = direction * distance
return step
def random_work(self):
"""随机漫步"""
while len(self.x_values) < self.num_points:
x_step = self.get_step()
y_step = self.get_step()
# 排除原地踏步的情况
if x_step == 0 and y_step == 0:
continue
# 计算下一个x,y 的坐标:上一步的坐标+下一步的移动距离
x = self.x_values[-1] + x_step
y = self.y_values[-1] + y_step
# 将x,y加入到x_values,y_values列表的末尾
self.x_values.append(x)
self.y_values.append(y)
2.matplotlib.py:绘制随机漫步图像
import matplotlib.pyplot as plt
from random_walk import RandomWalk
while True:
# 创建对象rw
rw = RandomWalk()
# 调用漫步方法
rw.random_work()
# dpi 表示像素
fig, ax = plt.subplots(figsize=(10, 6), dpi=128)
# 点数
num_points = range(rw.num_points)
# c表示颜色,s表示点的半径
ax.scatter(rw.x_values, rw.y_values, c=num_points, cmap=plt.cm.Blues, facecolor='none', s=1)
# 单独绘制起点终点,起点为绿色,终点为红色
ax.scatter(rw.x_values[0], rw.y_values[0], c='g', s=50)
ax.scatter(rw.x_values[-1], rw.y_values[-1], c='r', s=50)
# 隐藏坐标系
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
# 手动控制程序终止
conti = input("Another walk(y/n):")
if conti == 'n':
break
3.效果(每次运行刷新,都会得到不同的图像效果):