这对蒙蒂·霍尔来说是好还是坏的“模拟”?怎么会? [关闭]

2024-04-02

通过试图解释蒙蒂霍尔问题 http://en.wikipedia.org/wiki/Monty_Hall_problem昨天在课堂上给一位朋友说,我们最终用 Python 进行了编码,以证明如果你总是交换,你会赢 2/3 次。我们想出了这个:

import random as r

#iterations = int(raw_input("How many iterations? >> "))
iterations = 100000

doors = ["goat", "goat", "car"]
wins = 0.0
losses = 0.0

for i in range(iterations):
    n = r.randrange(0,3)

    choice = doors[n]
    if n == 0:
        #print "You chose door 1."
        #print "Monty opens door 2. There is a goat behind this door."
        #print "You swapped to door 3."
        wins += 1
        #print "You won a " + doors[2] + "\n"
    elif n == 1:
        #print "You chose door 2."
        #print "Monty opens door 1. There is a goat behind this door."
        #print "You swapped to door 3."
        wins += 1
        #print "You won a " + doors[2] + "\n"
    elif n == 2:
        #print "You chose door 3."
        #print "Monty opens door 2. There is a goat behind this door."
        #print "You swapped to door 1."
        losses += 1
        #print "You won a " + doors[0] + "\n"
    else:
        print "You screwed up"

percentage = (wins/iterations) * 100
print "Wins: " + str(wins)
print "Losses: " + str(losses)
print "You won " + str(percentage) + "% of the time"

我的朋友认为这是解决这个问题的好方法(并且是一个很好的模拟),但我有疑问和担忧。它实际上足够随机吗?

我遇到的问题是所有选择都是硬编码的。

对于蒙蒂·霍尔问题来说,这是一个好还是坏的“模拟”?怎么会?

你能想出一个更好的版本吗?


你的解决方案很好,但如果你想要对所提出的问题进行更严格的模拟(以及更高质量的Python;-),请尝试:

import random

iterations = 100000

doors = ["goat"] * 2 + ["car"]
change_wins = 0
change_loses = 0

for i in xrange(iterations):
    random.shuffle(doors)
    # you pick door n:
    n = random.randrange(3)
    # monty picks door k, k!=n and doors[k]!="car"
    sequence = range(3)
    random.shuffle(sequence)
    for k in sequence:
        if k == n or doors[k] == "car":
            continue
    # now if you change, you lose iff doors[n]=="car"
    if doors[n] == "car":
        change_loses += 1
    else:
        change_wins += 1

print "Changing has %s wins and %s losses" % (change_wins, change_loses)
perc = (100.0 * change_wins) / (change_wins + change_loses)
print "IOW, by changing you win %.1f%% of the time" % perc

典型的输出是:

Changing has 66721 wins and 33279 losses
IOW, by changing you win 66.7% of the time
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

这对蒙蒂·霍尔来说是好还是坏的“模拟”?怎么会? [关闭] 的相关文章

随机推荐