掷骰子的概率

Probability of a roll dice

我使用随机模块生成了 1,000,000 个随机数抽奖

import random
liste = []
for i in range(0, 1000000):
liste.append(random.uniform(0,1))

现在我必须使用 bins 选项将直方图中获得的值存储在 6 个 bins 中。 并在列表项上使用 if/else 条件,编写一个算法来模拟 1,000,000 次掷骰子的结果。 然后我必须计算每个值的出现频率并将其与预期概率 p = 1/6 进行比较。

请问有人知道怎么做吗,我不知道...

提前致谢!

编辑:关于 bins 选项

他们谈论这个:

import matplotlib.pyplot as plt
import numpy as np
# Création de la figure et des axes
fig, axs = plt.subplots(1, 1, sharey=True, tight_layout=True)
# Ajout de l'histogramme
axs.hist(valeurs, bins=np.arange(0.5, 7.5, 1), ec="black")
axs.set_title("Résultats jet dé")
axs.set_xlabel("Valeur dé")

使用@Roland_Smith的程序后,它给了我这个

 #import random
 #liste = []
 #for i in range(0, 1000000):
 #    liste.append(random.uniform(0,1))
 import random
 liste = random.choices((1,2,3,4,5,6), k=1000000)
 import collections
 c = collections.Counter(liste)
 print(c)

 p = [j/1e6 for j in c.values()]
 print(p)

 import matplotlib.pyplot as plt
 import numpy as np
 # Création de la figure et des axes
 fig, axs = plt.subplots(1, 1, sharey=True, tight_layout=True)
 # Ajout de l'histogramme
 axs.hist(c, bins=np.arange(0.5, 7.5, 1), ec="black")
 axs.set_title("Résultats jet dé")
 axs.set_xlabel("Valeur dé")

但问题是我的直方图看起来像这样

是每个数字出现的概率都一样正常还是不正常?

为 tdy 编辑

import matplotlib.pyplot as plt
import numpy as np
# Création de la figure et des axes
fig, axs = plt.subplots(1, 1, sharey=True, tight_layout=True)
# Ajout de l'histogramme
axs.hist(c,ec="black")
axs.set_title("Résultats jet dé")
axs.set_xlabel("Valeur dé")

在@JohanC 的帮助后编辑

#import random
#liste = []
#for i in range(0, 1000000):
#    liste.append(random.uniform(0,1))
import random
liste = random.choices((1,2,3,4,5,6), k=1000000)
import collections
c = collections.Counter(liste)
print(c)

p = [j/1e6 for j in c.values()]
print(p)

import matplotlib.pyplot as plt
import numpy as np
plt.bar(c.keys(), c.values())

# Création de la figure et des axes
#fig, axs = plt.subplots(1, 1, sharey=True, tight_layout=True)
# Ajout de l'histogramme
#axs.hist(c,ec="black")
#axs.set_title("Résultats jet dé")
#axs.set_xlabel("Valeur dé")

我得到每个骰子面的值 160000,即 6。但是 6*160000+960000 我不应该得到掷骰数,即 1000000?

掷骰子产生一个整数值。

所以使用random.uniform(其中returns一个float)不是正确的方法。

尝试:

import random
liste = random.choices((1,2,3,4,5,6), k=1000000)

然后,我将使用 collections.Counter 来计算值:

import collections
c = collections.Counter(liste)
print(c)

这会让你得到类似的东西:

Counter({6: 167399, 5: 167083, 2: 166789, 3: 166548, 1: 166236, 4: 165945})

计算概率:

p = [j/1e6 for j in c.values()]

这产生:

[0.167083, 0.165945, 0.167399, 0.166789, 0.166548, 0.166236]

用于绘图;

import matplotlib.pyplot as plt

plt.bar(c.keys(),p)
plt.show()

它将看起来像这样:

所有条形看起来都差不多的原因是因为它们

让我们检查一下 p 和骰子公平的概率之间的差异,即 1/6:

[round(j-1/6, 6) for j in p]

这给出:

[0.000416, -0.000722, 0.000732, 0.000122, -0.000119, -0.000431]

所以实际计算出的概率与公平骰子的概率非常接近。