提问者:小点点

决定每一掷骰子的赔率


当玩游戏时,你必须掷两个骰子,知道每一个骰子的赔率是很好的。 例如,滚出12的几率约为3%,滚出7的几率约为17%。

你可以用数学计算这些,但是如果你不懂数学,你可以写一个程序来完成。 要做到这一点,你的程序应该模拟滚动两个骰子大约10,000次,然后计算并打印出2,3,4,的百分比。 。。,12。

滚动2个骰子的状态空间

首先,我的问题来自概率百分比。 考虑到在36种可能性的状态空间中,只有6种可能性可以给出12种可能性,为什么概率是3呢?

正因为如此,我一直无法完成我的程序。 下面是我尝试的解决方案

from random import randint
dice_roll=[]
outcome =(2,3,4,5,6,7,8,9,10,11,12)
sim =10

for simulations in range(sim):
    first_dice_roll = randint(1,6)
    second_dice_roll = randint(1,6)

    dice_roll.append(first_dice_roll + second_dice_roll)
    sumi = sum(dice_roll)
print(dice_roll,"Dice roll")

共3个答案

匿名用户

你应该计算你看到每一个总和的次数(collections.counter很容易,但是你也可以使用字典)。 最后你可以除以卷数得到百分比:

from random import randint
from collections import Counter

dice_counts = Counter()

sim = 10000

for simulations in range(sim):
    first_dice_roll = randint(1,6)
    second_dice_roll = randint(1,6)

    dice_counts[first_dice_roll + second_dice_roll] += 1

print(dice_counts)
# Counter({7: 1624, 8: 1421, 6: 1346, 5: 1120, 9: 1112, 4: 879, 10: 835, 3: 554, 11: 540, 2: 295, 12: 274})

print("percent rolled 12:", dice_counts[12]/ sim)
#  0.0274 (give or take)

匿名用户

我稍微修改了你的代码。 我用字典替换了结果列表,其中键是和,值是和出现的频率。 代码的输出也贴在下面。 你可以在下面看到骰子滚动的概率接近于数学上的预期。

注意:Python为randint使用了一个伪随机数生成器,这不是一个很好的近似,但不是真正的随机

from random import randint
outcome = {2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0} #map of sum:freq
sim =100000

for simulations in range(sim):
    first_dice_roll = randint(1,6)
    second_dice_roll = randint(1,6)
    sum_dice = first_dice_roll + second_dice_roll
    outcome[sum_dice] += 1 
    
for key in outcome.keys():
    print("Percentage for rolling a sum of %s is: %s"%(key,outcome[key]/sim*100))

输出量

Percentage for rolling a sum of 2 is: 2.775
Percentage for rolling a sum of 3 is: 5.48
Percentage for rolling a sum of 4 is: 8.179
Percentage for rolling a sum of 5 is: 11.029
Percentage for rolling a sum of 6 is: 13.831
Percentage for rolling a sum of 7 is: 16.997
Percentage for rolling a sum of 8 is: 13.846
Percentage for rolling a sum of 9 is: 11.16
Percentage for rolling a sum of 10 is: 8.334999999999999
Percentage for rolling a sum of 11 is: 5.5489999999999995
Percentage for rolling a sum of 12 is: 2.819

匿名用户

使用字典方法:

import random

rolls = {2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0}

for i in range(0,10000):
    first_roll = random.randint(1,6)
    second_roll = random.randint(1,6)
    rolls[first_roll + second_roll] += 1

for k,v in rolls.items():
    print(f"Percent Rolled:{k}={v / 10000}%")

输出:

Percent Rolled:2=0.0275%
Percent Rolled:3=0.052%
Percent Rolled:4=0.0834%
Percent Rolled:5=0.1123%
Percent Rolled:6=0.1394%
Percent Rolled:7=0.1652%
Percent Rolled:8=0.1413%
Percent Rolled:9=0.1102%
Percent Rolled:10=0.0853%
Percent Rolled:11=0.0554%
Percent Rolled:12=0.028%

该解决方案执行循环10,000次并更新卷字典,然后打印出每个卷的百分比。

您还可以通过以下操作轻松获得一定的滚转百分比:

print(f"11 Was Rolled: {rolls[11] / 10000}%")

输出:

"11 Was Rolled: 0.0554%"