【问题标题】:Simulate rolling 2 dice 24 times and calculating the probability of getting a 6 in Python模拟掷 2 个骰子 24 次并在 Python 中计算得到 6 的概率
【发布时间】:2019-02-03 23:18:47
【问题描述】:

我正在尝试模拟 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)

请帮忙!谢谢!

【问题讨论】:

  • 无法复制。给我大约 0.49。
  • 在第一种情况下,您似乎拥有自己的randint 实现。它不需要3个参数。在第二种情况下,请说明在掷两个骰子 24 次时是要双 6 还是 any 6,因为 any 6 的概率是 99.984%。我假设您的意思是掷两个骰子 24 倍并获得双 6,即 49.14%。

标签: python simulation probability


【解决方案1】:

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.

【讨论】:

    【解决方案2】:

    randint(1,7) 可能返回 7。

    也不用is来比较整数

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

    【讨论】:

    • 没有is比较。
    • 你说得对,我在输入错误的行中看到了原样 if 6 in randint(1,7,(4)):
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    相关资源
    最近更新 更多