我有這段代碼計算隨機游走,我試圖找到所有游走的從 (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()
uj5u.com熱心網友回復:
您可以從繪制的坐標的距離steps來0,0使用distance=np.linalg.norm(steps, axis=1)。然后你可以取這個陣列的最大值來找到最大距離。然后,您可以為繪圖和圖例添加標簽。見下面的代碼:
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")
max_distance=np.zeros(repeats)
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]
distance=np.linalg.norm(steps, axis=1)
max_distance[x]=np.amax(distance)
plt.plot(xs, ys,label='Random walk ' str(x) ': max distance: ' str(np.round(max_distance[x],1)))
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.legend(fontsize=8)
plt.show()
輸出給出:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/362245.html
標籤:Python 麻木的 matplotlib 视觉工作室代码 随机游走
