如何计算随机游走距原点(0,0)的最大距离并添加到matplotlib图例中
实现效果说明
以下代码在原有逻辑基础上新增了全局最大距离统计,修复了变量重名bug,已将所有路径到原点的最大距离、预期半径等值整合到matplotlib图例中,可直接运行:
import numpy as np import matplotlib.pyplot as plt import math np.random.seed(12) repeats = 5 N_steps = 1000000 expected_R = np.sqrt(N_steps) plt.title(f"{repeats} random walks of {N_steps} steps") # 初始化全局最大距离变量 global_max_dist = 0 # 把循环变量从x改成idx,避免和后面的变量重名冲突 for idx in range(repeats): dirs = np.random.randint(0, 4, N_steps) steps = np.empty((N_steps, 2)) steps[dirs == 0] = [0, 1] # 0 - 上 steps[dirs == 1] = [0, -1] # 1 - 下 steps[dirs == 2] = [1, 0] # 2 - 右 steps[dirs == 3] = [-1, 0] # 3 - 左 steps = steps.cumsum(axis=0) print("Final position:", steps[-1]) # 计算当前路径所有点到原点的欧氏距离 point_dists = np.sqrt(np.sum(np.square(steps), axis=1)) current_max = point_dists.max() # 更新全局最大距离 if current_max > global_max_dist: global_max_dist = current_max skip = N_steps // 5000 + 1 xs = steps[::skip, 0] ys = steps[::skip, 1] # 绘图时标注单条路径的最大距离,不需要可以删掉label参数 plt.plot(xs, ys, label=f"路径{idx+1} 最大距离:{current_max:.1f}") # 绘制预期半径圆,添加图例标注 circle = plt.Circle((0, 0), radius=expected_R, color="k", fill=False, label=f"预期R={expected_R:.1f}") plt.gcf().gca().add_artist(circle) # 把全局最大距离加入图例 plt.plot([], [], ' ', label=f"全部路径最大距离:{global_max_dist:.1f}") plt.gcf().gca().set_aspect("equal") max_range = 1500 + int(global_max_dist) + 100 plt.axis([-max_range, max_range, -max_range, max_range]) # 渲染图例 plt.legend() plt.show()
核心修改点
- 新增欧氏距离计算逻辑:用
np.sqrt(np.sum(np.square(steps), axis=1))批量计算路径上所有点到原点的距离 - 新增全局最大距离统计逻辑,遍历所有路径后得到全量样本的最大距离
- 修复原代码中循环变量
x与后续自定义变量重名的bug,避免坐标轴范围计算错误 - 通过空折线的方式将全局最大距离添加到图例中,同时支持单条路径标注各自的最大距离
- 原代码中圆默认是填充黑色,这里修改为
fill=False避免遮挡游走路径,和参考图效果一致,不需要可以删掉该参数
内容的提问来源于stack exchange,提问作者Humanperson
相关产品推荐
相关产品推荐

