gpt4 book ai didi

python - 100 步 100 名随机游走者的平均值

转载 作者:行者123 更新时间:2023-12-05 05:50:42 24 4
gpt4 key购买 nike

我被要求编写 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()

最佳答案

像这样修改你的代码:

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()

enter image description here

更新

How can I calculate the root mean square of this array?

# Remove the time dimension, extract the position
arr = walkers[:, 1]

# Compute the Root Mean Square
rms = np.sqrt(np.mean(arr**2, axis=1))

关于python - 100 步 100 名随机游走者的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70487162/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com