gpt4 book ai didi

python - 这对 Monty Hall 来说是好还是坏 'simulation'?怎么来的?

转载 作者:IT老高 更新时间:2023-10-28 21:06:17 26 4
gpt4 key购买 nike

通过试图解释Monty Hall problem昨天在类里面给一个 friend ,我们最终用 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"

我的 friend 认为这是一个很好的方法(并且是一个很好的模拟),但我有我的怀疑和担忧。它真的足够随机吗?

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

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

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

最佳答案

您的解决方案很好,但如果您想要更严格地模拟所提出的问题(以及更高质量的 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

关于python - 这对 Monty Hall 来说是好还是坏 'simulation'?怎么来的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1247863/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com