我被要求撰寫 100 個隨機游走者的代碼,每個都有 1000 步。然后繪制 100 名步行者的平均步數。我能夠在一個圖中繪制所有步行者,但找不到繪制平均值的方法。任何幫助將不勝感激。謝謝。
這是我的代碼:
import numpy as np
import matplotlib.pyplot as plt
import random
# 1
N = 100
for j in range(N):
def randomwalk1D(n):
x, t = 0, 0
# Generate the time points [1, 2, 3, ... , n]
time = np.arange(n 1)
position = [x]
directions = [1, -1]
for i in range(n):
# Randomly select either 1 or -1
step = np.random.choice(directions)
# Move the object up or down
if step == 1:
x = 1
elif step == -1:
x -= 1
# Keep track of the positions
position.append(x)
return time, position
rw = randomwalk1D(1000)
plt.plot(rw[0], rw[1], 'r-', label="rw")
plt.show()
uj5u.com熱心網友回復:
像這樣修改你的代碼:
import numpy as np
import matplotlib.pyplot as plt
import random
# 1
N = 100
walkers = [] # HERE
for j in range(N):
def randomwalk1D(n):
x, t = 0, 0
# Generate the time points [1, 2, 3, ... , n]
time = np.arange(n 1)
position = [x]
directions = [1, -1]
for i in range(n):
# Randomly select either 1 or -1
step = np.random.choice(directions)
# Move the object up or down
if step == 1:
x = 1
elif step == -1:
x -= 1
# Keep track of the positions
position.append(x)
return time, position
rw = randomwalk1D(1000)
walkers.append(rw)
plt.plot(rw[0], rw[1], 'r-', label="rw")
walkers = np.array(walkers) # HERE
plt.plot(walkers[0][0], walkers[:, 1].mean(axis=0), 'b-', label="mean") # HERE
plt.show()

更新
如何計算此陣列的均方根?
# Remove the time dimension, extract the position
arr = walkers[:, 1]
# Compute the Root Mean Square
rms = np.sqrt(np.mean(arr**2, axis=1))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/394386.html
標籤:Python matplotlib 平均 随机游走
上一篇:如何創建適合高斯分布的3D資料集
