我使用隨機模塊生成了 1,000,000 個亂數抽獎
import random
liste = []
for i in range(0, 1000000):
liste.append(random.uniform(0,1))
現在我必須使用 bins 選項將直方圖中獲得的值存盤在 6 個 bin 中。并在串列項上使用 if/else 條件,撰寫一個演算法來模擬 1,000,000 次擲骰子的結果。然后我必須計算每個值的出現頻率并將其與預期概率 p = 1/6 進行比較。
請問有誰知道怎么做,我不知道...
提前致謝!
編輯:關于垃圾箱選項
他們談論這個:
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é")

i get a value of 160000 for each dice face, i.e. 6. but 6*160000 960000 i shouldn't get the number of rolls, i.e. 1000000?
uj5u.com熱心網友回復:
擲骰子產生一個整數值。
所以使用random.uniform(回傳 a 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]
所以實際計算的概率非常接近公平骰子的概率。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/424627.html
上一篇:按月在海上小提琴圖中設定x范圍
