作为一个练习,我正在编写一个程序来计算掷出相同数字的 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) .
我的程序有问题吗?还是我在这里的数学上犯了一些基本错误?或者,如果我能够在更大的迭代中运行程序,我会发现我的结果更接近正确答案吗?