#
# Monty Hall Problem Simulation
# Author: Ryan Sturmer
#
import random
def play_round(doors, switch):
# Choose the location of the car
car = random.randint(1, doors)
# Contestant chooses a door
initial_choice = random.randint(1, doors)
# Monty opens ALL the other doors except one
if initial_choice != car:
monty_leaves = car # If the car wasn't chosen, Monty is forced to reveal its location
else:
while True:
monty_leaves = random.randint(1, doors)
if monty_leaves != initial_choice:
break
# monty_leaves is now the door that Monty DIDN'T open
if switch:
final_choice = monty_leaves
else:
final_choice = initial_choice
victory = (final_choice == car)
return victory, initial_choice, final_choice, car
def simulation(iterations, doors=3):
games_won_switch = 0
games_won_noswitch = 0
for i in range(iterations):
won_game, intial_choice, final_choice, car = play_round(doors, False)
if(won_game):
games_won_noswitch += 1
won_game, intial_choice, final_choice, car = play_round(doors, True)
if(won_game):
games_won_switch += 1
print ""
print " Monty Hall Simulation"
print "---------------------------------------------"
print " Iterations: %d" % iterations
print " Games won when switching doors: %d (%g%%)" % (games_won_switch, 100*float(games_won_switch)/float(iterations))
print "Games won when NOT switching doors: %d (%g%%)" % (games_won_noswitch, 100*float(games_won_noswitch)/float(iterations))
=============================================== ============================
我从github找到了这段代码。 当我运行此代码时,games_won_switch和games_won_noswitch的总和不等于迭代。 (例如,如果我设置迭代1,000 - >它出现996,1,001,1,008不精确1,000)
我如何解决这个问题呢?
答案 0 :(得分:1)
代码中没有错误;它运行模拟两次:
一旦玩家选择每次都切换门,而另一次玩家选择永不切换门。然后打印两次模拟的结果。
结果来自独立模拟。
for i in range(iterations):
# Sim with player choose to open the door each time
won_game, intial_choice, final_choice, car = play_round(doors, False)
if(won_game):
games_won_noswitch += 1
# Sim with player choose NEVER to open the door
won_game, intial_choice, final_choice, car = play_round(doors, True)
if(won_game):
games_won_switch += 1
因此,由于sim(open=True)
不是(1 - sim(open=False))
,而是来自两组模拟的结果,因此结果的添加可能不会恰好与试验次数相加。