本篇博客将使用 Python 来 生成随机漫步数据,再使用 Matplotlib 库,将以引人注目的方式将这些数据呈现出来。
随机漫步 顾名思义就是随机走出的步伐,它是这样行走得到的路径:每次行走都是完全随机的、没有明确的方向,结果是由一系列随机决策决定的。我们可以将随机漫步看作是 蚂蚁在晕头转向 的情况下,每次都沿随机的方向前行所经过的路径。
为模拟随机漫步,首先创建一个名为 RandomWalk 的类,其作用是 随机的选择前进方向。这个类需要三个属性:一个是 存储随机漫步次数的变量,其他两个是 列表,分别存储随机漫步经过的每个点的 x 坐标 和 y 坐标。
RandomWalk 类只包含两个方法:
from random import choice class RandomWalk: '''一个生成随机漫步数据的类''' def __init__(self, num_points = 500): '''初始化随机漫步的属性''' self.num_points = num_points # 所有随机漫步都使于(0,0) self.x_values = [0] self.y_values = [0]
我们将使用方法 fill_walk() 来生成 漫步包含的点,并 决定每次漫步的方向。
import random def fill_walk(self): '''计算随机漫步包含的所有点''' # 不断漫步,直到列表达到指定的长度 while len(self.x_values) < self.num_points: # 决定前进方向以及沿这个方向前进的距离 x_direction = random.choice([1,-1]) x_distance = random.choice([0,1,2,3,4]) x_step = x_direction * x_distance y_direction = random.choice([1,-1]) y_distance = random.choice([0,1,2,3,4]) y_step = y_direction * y_distance # 拒绝原地踏步 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 self.x_values.append(x) self.y_values.append(y)
下面的代码将随机漫步的所有点都绘制出来:
from random import choice import matplotlib.pyplot as plt 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_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 值 x = self.x_values[-1] + x_step y = self.y_values[-1] + y_step self.x_values.append(x) self.y_values.append(y) # 创建一个 RandomWalk 实例 random_wander = RandomWalk() random_wander.fill_walk() # 将所有的点都绘制出来 plt.style.use('classic') (fig,ax) = plt.subplots() ax.scatter(random_wander.x_values, random_wander.y_values, s = 15) plt.show()
这篇文章主要讲解了随机漫步相关知识点。