我正在学习 MIT OpenCourseWare 计算机编程入门类(class),我不确定我是否以正确的方式解决了一个简单的模拟问题。
- What is the probability of rolling a Yahtzee! on the first roll? That is, what is the probability of rolling five 6-sided dice, and having them all display the same number?
- Write a Monte Carlo simulation to solve the above problem (the Yahtzee problem), and submit your code as
所以滚动 Yahtzee 的概率是 1/1296 或大约 .077%
这是我运行模拟的代码:
import random
def runYahtzee(numTrials):
"""Runs the classes version of the yahtzee simulation"""
success = 0
for i in range(numTrials):
dices = []
for i in range(6):
dices.append(random.randrange(1,7))
#print dices
state = True
for dice in dices:
if dice != dices[0]:
state = False
if state == True:
print "You got a Yahtzee"
print dices
success += 1
print "numTrials is: " + str(numTrials)
print "Success is: " + str(success)
rate = float(success)/numTrials
return rate
runYahtzee(10000000)
多次运行该程序,我每次都得到大约 .0001258。这是 0.012%,但实际概率约为 0.077%。我在这里做错了什么吗?
请您参考如下方法:
你做错的是掷 6 个骰子而不是 5 个。
0.001258 * 6 = 0.0007548
...接近您的 0.077%
改变你的循环:
for i in range(5):
顺便说一句,复数是dice;单数是die。 dices 是错误的,除非你想变得有趣。在这种情况下,您可以使用单数形式的“douse”...never say die!
