简单的Yahtzee模拟不能给出正确的结果?

2024-06-11 01:00:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习麻省理工学院计算机编程课程的开放式课件简介,我不确定我是否正确地解决了一个简单的模拟问题。在

  1. 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?
  2. 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%。我有什么地方做错了吗?在


Tags: andoftheinforisdicesuccess
2条回答

你做错的是掷6个骰子而不是5个骰子。在

0.001258*6=0.0007548

。。。接近你的0.077%

改变你的循环:

    for i in range(5):

顺便说一句,复数是dice;单数是diedices是错的,除非你想逗乐。在这种情况下,你可以用单数的“灌水”。。。永远不要说死!在

下面是我如何编写它(Python3):

from collections import Counter
from random import randint

def roll():
    return randint(1, 6)

def is_yahtzee(num_dice = 5):
    first = roll()
    return all(roll() == first for _ in range(1, num_dice))

def montecarlo(fn, num_trials):
    return Counter(fn() for _ in range(num_trials))

def main():
    num_trials = 10000000
    result = montecarlo(is_yahtzee, num_trials)
    prob = result[True] / num_trials
    print(
        "After {} trials, probability of Yahtzee is {:0.5f}%"
        .format(num_trials, 100. * prob)
    )

if __name__ == "__main__":
    main()

它跑起来像

^{pr2}$

注意,保持函数的简短通常会使它们更易于理解和测试。在

相关问题 更多 >