【发布时间】:2021-12-31 09:56:27
【问题描述】:
我有这段代码计算随机游走,我试图找到所有游走的最大距离(0.0)并将它们添加到图例中。添加了我想要达到的结果的图像。
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")
for x in range(repeats):
dirs = np.random.randint(0, 4, N_steps)
steps = np.empty((N_steps, 2))
steps[dirs == 0] = [0, 1] # 0 - right
steps[dirs == 1] = [0, -1] # 1 - left
steps[dirs == 2] = [1, 0] # 2 - up
steps[dirs == 3] = [-1, 0] # 3 - down
steps = steps.cumsum(axis=0)
print("Final position:", steps[-1])
skip = N_steps // 5000 + 1
xs = steps[::skip, 0]
ys = steps[::skip, 1]
x = max(ys)
plt.plot(xs, ys)
circle = plt.Circle((0, 0), radius=expected_R, color="k")
plt.gcf().gca().add_artist(circle)
plt.gcf().gca().set_aspect("equal")
plt.axis([-1500-x,1500+x,-1500-x,1500+x])
plt.show()
【问题讨论】:
标签: python numpy matplotlib visual-studio-code random-walk