确定每卷骰子的几率

Determining the odds of each roll of dice

在玩必须掷两次骰子的游戏时,知道每次掷骰的几率是件好事。例如,掷出 12 的几率约为 3%,掷出 7 的几率约为 17%。

你可以用数学方法计算这些,但如果你不懂数学,你可以写一个程序来计算。为此,您的程序应该模拟掷两个骰子大约 10,000 次并计算并打印出结果为 2, 3, 4, . 的卷的百分比。 . . , 12.

State Space for rolling 2 dice

首先我的问题来自概率百分比。考虑到只有六个可以给出十二个状态 space 的 36 种可能性 为什么概率是 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")

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

注意: 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

我的解决方案:

from random import randint

probs = {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(10000):
    diceTotal = randint(1,6)+randint(1,6)
    
    probs[diceTotal] += 1

for key,value in probs.items():
    print(str(key) + " => " + str(value/100) + "%")

Each possible total is a key in a dictionary and its value is incremented whenever that total is the result of the dice rolling.

输出:

2 => 2.8%
3 => 5.64%
4 => 7.96%
5 => 11.44%
6 => 13.68%
7 => 16.42%
8 => 13.81%
9 => 11.47%
10 => 8.55%
11 => 5.54%
12 => 2.69%

结果非常接近理论概率。增加掷骰数当然会提高估计值。