模拟掷 2 个骰子 24 次并计算 Python 中得到 6 的概率

Simulate rolling 2 dice 24 times and calculating the probability of getting a 6 in Python

我正在尝试模拟 Chevalier de Mere 的骰子投注 1000 次以估计每次投注获胜的概率。我模拟事件 掷骰子 4 次时出现 6,我得到的结果与我的预期相似 (~0.5)。但是,当模拟掷两个骰子 24 次出现 6 的事件时,我得到的结果高于预期。当我期望 ~ 0.49 时,我得到 ~0.6。

是我运行模拟的方式有问题,还是有别的解释?见代码:

total = 0
for i in range(1000):
    if 6 in randint(1,7,(4)):
        total +=1
print("The probability a 6 turns up when rolling 1 die 4 times is:",total/1000)

total = 0
for i in range(1000):
    for j in range(24):
        if 6 == randint(1,7) and 6 == randint(1,7):
            total +=1
print("The probability a 6 turns up when rolling 2 die 24 times is:",total/1000)

请帮忙!谢谢!

random.randint(a,b) 包括端点 ab,因此使用 random.randint(1,6).

假设您在第二种情况下指的是双 6,那么您在每次试验中多次计算双 6。计算所有 24,然后检查双 6 的任何实例。

这是工作代码 (Python 3.6):

from random import randint

trials = 1000

total = 0
for i in range(trials):
    if 6 in [randint(1,6) for j in range(4)]:
        total +=1
print(f'A 6 appeared when rolling 1 die 4 times {total/trials:.2%} of the time.')

total = 0
for i in range(trials):
    if (6,6) in [(randint(1,6),randint(1,6)) for j in range(24)]:
        total +=1
print(f'Double 6s appeared when rolling 2 dice 24 times {total/trials:.2%} of the time.')

输出:

A 6 appeared when rolling 1 die 4 times 50.30% of the time.
Double 6s appeared when rolling 2 dice 24 times 48.90% of the time.

randint(1,7) 可能 return 7.

也不要用is来比较int

并且在第一个实验中,您缺少一个循环 for k in range(4) 并且有一个奇怪的第三个参数范围。打字错误?