100个随机行走者进行1000步行走的平均值

3

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

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

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

enter image description here

更新

如何计算这个数组的均方根?

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

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

完成了,我刚开始使用Stack Overflow。我有一个最后的问题,如何计算这个数组的均方根?预测数组全部为零。 - Majdi Assaid
我根据你的评论更新了我的答案。 - Corralien
抱歉打扰您,我有最后一个问题,如何找到均方位移?谢谢。 - Majdi Assaid
什么是均方位移 - Corralien
你的意思是:rms = np.sqrt(np.mean(arr**2, axis=0)) 吗?(axis=0) - Corralien
说实话,我现在也不太确定了。我会保持原样。谢谢! - Majdi Assaid

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接