Jos*_*unt 17 python language-agnostic probability
通过尝试在昨天的课堂上向朋友解释Monty Hall问题,我们最终用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"
Run Code Online (Sandbox Code Playgroud)
我的朋友认为这是一个很好的方式(并且是一个很好的模拟),但我有疑虑和担忧.它实际上是随机的吗?
我遇到的问题是所有的选择都是硬编码的.
这对蒙蒂霍尔问题来说是一个好的还是坏的"模拟"?怎么会?
你能想出一个更好的版本吗?
Ale*_*lli 37
你的解决方案很好,但是如果你想要对问题进行更严格的模拟(和更高质量的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
Run Code Online (Sandbox Code Playgroud)
典型的输出是:
Changing has 66721 wins and 33279 losses
IOW, by changing you win 66.7% of the time
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12289 次 |
| 最近记录: |