【学习】人工智能初学——模拟轮换门抽奖
问题描述
顾客参加一个抽奖活动,三个关闭的门后面只有一个有奖品,顾客选择一个门之后,主持人会打开一个没有奖品的门,并给顾客一次改变选择的机会。此时,改选另外一个门会得到更大的获奖几率么?
程序模拟
def DoorAndPrizeSim(switch, loopNum):
win = 0
total = 0
for loop in range(loopNum):
prize = random.randint(0, 2) # 奖品所在门的编号
initialChoice = random.randint(0, 2) # 顾客随机选择门的编号
doors = [0, 1, 2] # 设置0,1,2三扇门
doors.remove(prize)
"""
主持人需要打开一扇非中奖门非顾客选择门,所以需要进行两次remove
"""
if (initialChoice in doors):
doors.remove(initialChoice)
n = len(doors)
r = random.randint(0, n - 1)
openDoor = doors[r] # 主持人打开的门
if (switch):
secondChoice = 3 - openDoor - initialChoice # 换门,仅剩一个门可选,该门的编号是"3 - openDoor - initialChoice"
else:
secondChoice = initialChoice # 不换门
total += 1
if (secondChoice == prize):
win += 1
return (win / total)
print("一百万次模拟换门并中奖的概率:", DoorAndPrizeSim(True, 1000000))
print("一百万次模拟不换门并中奖的概率:", DoorAndPrizeSim(False, 1000000))
实验结论
- 一百万次模拟换门并中奖的概率: 0.667242
- 一百万次模拟不换门并中奖的概率: 0.333508