【问题标题】:Average of 100 random walkers with 1000 steps100 个随机步行者的平均值,每步 1000 步
【发布时间】:2022-01-25 22:15:34
【问题描述】:

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

【问题讨论】:

  • 你知道如何计算平均值吗?
  • 是的,所有步行的总和除以步行次数。但我不知道如何在我的代码中实现它

标签: python matplotlib average random-walk


【解决方案1】:

像这样修改你的代码:

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

【讨论】:

  • 完成,我刚开始使用堆栈溢出。我有最后一个问题,如何计算这个数组的均方根?预测的数组全为零。
  • 我根据您的评论更新了我的答案。
  • 很抱歉打扰您,我还有最后一个问题,如何求均方位移?谢谢。
  • 什么是均方位移
  • 你的意思是:rms = np.sqrt(np.mean(arr**2, axis=0))? (轴=0)
猜你喜欢
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-23
  • 1970-01-01
  • 2014-07-29
  • 2019-01-28
  • 1970-01-01
相关资源
最近更新 更多