我正在学习麻省理工学院计算机编程课程的开放式课件简介,我不确定我是否正确地解决了一个简单的模拟问题。在
- 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
所以摇一个雅特兹的概率是1/1296或0.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)
多次运行这个程序,每次都是0.0001258左右。这是0.012%,但实际概率约为0.077%。我有什么地方做错了吗?在
你做错的是掷6个骰子而不是5个骰子。在
0.001258*6=0.0007548
。。。接近你的0.077%
改变你的循环:
顺便说一句,复数是
dice
;单数是die
。dices
是错的,除非你想逗乐。在这种情况下,你可以用单数的“灌水”。。。永远不要说死!在下面是我如何编写它(Python3):
它跑起来像
^{pr2}$注意,保持函数的简短通常会使它们更易于理解和测试。在
相关问题 更多 >
编程相关推荐