为什么 for 循环不将每次迭代中的每个 roll 值保存到直方图中?

Why doesn't the for loop save each roll value in each iteration to the histogram?

我正在创建一个 for 循环来检查掷骰子对均值的回归。 想要的结果是直方图显示每次迭代出现的所有滚动值。

为什么 for 循环不将每次迭代中的每个滚动值保存到直方图中?

此外,如果 n>20000 个值,PyCharm 将永远加载,因此在这种情况下代码无法完全执行。

import numpy as np

import matplotlib.pyplot as plt

sums = 0

values = [1, 2, 3, 4, 5, 6]

numbers = [500, 1000, 2000, 5000, 10000, 15000, 20000, 50000, 100000]

n = np.random.choice(numbers)

for i in range(n):

    roll = np.random.choice(values) + np.random.choice(values)
    sums = roll + sums
    h, h2 = np.histogram(sums, range(2, 14))
    plt.bar(h2[:-1], h / n)
    plt.title(n)
plt.show()

Current output

您现在在每次迭代中都覆盖了 h 和 h2。相反,您可以将值附加到列表并制作整个列表的直方图:

import numpy as np

import matplotlib.pyplot as plt

sums = 0

values = [1, 2, 3, 4, 5, 6]

numbers = [500, 1000, 2000, 5000, 10000, 15000, 20000, 50000, 100000]

n = np.random.choice(numbers)

all_rolls = []

for i in range(n):

    roll = np.random.choice(values) + np.random.choice(values)
    all_rolls.append(roll)
h, h2 = np.histogram(all_rolls, range(2, 14))
plt.bar(h2[:-1], h / n)
plt.title(n)
plt.show()

输出: