2

作为一个练习,我正在编写一个程序来计算掷出相同数字的 5 个骰子的几率。这个想法是通过模拟而不是简单的数学来获得结果。我的程序是这样的:

# rollFive.py

from random import *

def main():
    n = input("Please enter the number of sims to run: ")
    hits = simNRolls(n)
    hits = float(hits)
    n = float(n)
    prob = hits/n
    print "The odds of rolling 5 of the same number are", prob

def simNRolls(n):
    hits = 0
    for i in range(n):
        hits = hits + diceRoll()
    return hits


def diceRoll():
    firstDie = randrange(1,7,1)
    for i in range(4):
        nextDie = randrange(1,7,1)
        if nextDie!=firstDie:
            success = 0
            break
        else:
            success = 1
    return success

问题是运行这个程序的 n 值为 1 000 000 给我的概率通常在 0.0006 到 0.0008 之间,而我的数学让我相信我应该得到更接近 0.0001286 的答案(又名 (1/6)^5) .

我的程序有问题吗?还是我在这里的数学上犯了一些基本错误?或者,如果我能够在更大的迭代中运行程序,我会发现我的结果更接近正确答案吗?

4

4 回答 4

6

得到一个特定数字五次的概率是 (1/6)^5,但是得到任何五个相同的数字的概率是 (1/6)^4。

有两种方法可以看到这一点。

首先,例如,得到全 1 的概率是 (1/6)^5,因为六分之二只有一个得到 1。乘以五个骰子,你得到 (1/6)^5 . 但是,既然有六个可能的数字可以得到相同的结果,那么就有六种方法可以成功,即 6((1/6)^5) 或 (1/6)^4。

换个角度看,第一卷给出什么并不重要,所以我们排除它。然后我们必须将该数字与剩余的四个掷骰相匹配,其概率为 (1/6)^4。

于 2009-09-24T01:52:56.377 回答
1

你的数学是错误的。得到五个相同数字的骰子的概率是6*(1/6)^5 = 0.0007716

于 2009-09-24T01:53:33.077 回答
1

Very simply, there are 6 ** 5 possible outcomes from rolling 5 dice, and only 6 of those outcomes are successful, so the answer is 6.0 / 6 ** 5

于 2009-09-24T11:25:15.520 回答
0

I think your expected probability is wrong, as you've stated the problem. (1/6)^5 is the probability of rolling some specific number 5 times in a row; (1/6)^4 is the probability of rolling any number 5 times in a row (because the first roll is always "successful" -- that is, the first roll will always result in some number).

>>> (1.0/6.0)**4
0.00077160493827160479

Compare to running your program with 1 million iterations:

[me@host:~] python roll5.py 
Please enter the number of sims to run: 1000000
The odds of rolling 5 of the same number are 0.000755
于 2009-09-24T01:57:29.467 回答