[Monty Hall Problem](https://ja.wikipedia.org/wiki/%E3%83%A2%E3%83%B3%E3%83%86%E3%82%A3%E3%83%BB% E3% 83% 9B% E3% 83% BC% E3% 83% AB% E5% 95% 8F% E9% A1% 8C) is a mysterious "subjective answer and probability-based answer do not match" It's a problem. This time, I wrote a simple simulation program for this "Monty Hall problem". Long live the empiricism!
import random
def monty_hall():
# 0,1,The correct answer is randomly selected from the door of 2
answer = random.randrange(3)
#Answerer is 0,1,Choose your favorite door from 2
first_choice = random.randrange(3)
#The moderator, Monty, opens one door on the outskirts
monty_choice = random.choice(tuple({0, 1, 2} - {answer, first_choice}))
#The answerer chooses a different door than the one he chose first as the second choice.
second_choice = ({0, 1, 2} - {first_choice, monty_choice}).pop()
#Is the door you chose the second time the correct answer??
return answer == second_choice
if __name__ == '__main__':
for x in (10, 100, 1000, 100000):
#During x trials, monty_hall()Records the number of times that returned True.
win = sum(1 for _ in range(x) if monty_hall())
print("Number of trials{0}Probability of times: {1}".format(x, win / x))
#Probability when the number of trials is 10: 0.7
#Probability when the number of trials is 100: 0.58
#Probability when the number of trials is 1000: 0.673
#Probability when the number of trials is 100000: 0.66657
The biggest issue in the "Monty Hall problem" is "should the challenger change the first choice after the moderator shows the door out?", But "there is a higher probability that changing it is the correct answer." It was confirmed that.
By the way, the above code is written in a slightly verbose way for clarity, but it can also be refactored as follows:
def refactoring_month_hall():
# 0,1,The correct answer is randomly selected from the door of 2
answer = random.randrange(3)
#Answerer is 0,1,Choose your favorite from the 2 doors
first_choice = random.randrange(3)
#The first door you chose is not the correct answer=>Another door is correct
return answer != first_choice
if __name__ == '__main__':
for x in (10, 100, 1000, 10000, 100000):
win = sum(1 for _ in range(x) if refactoring_month_hall())
print("Number of trials{0}Probability of times: {1}".format(x, win / x))
#Probability when the number of trials is 10: 0.8
#Probability when the number of trials is 100: 0.65
#Probability when the number of trials is 1000: 0.678
#Probability when the number of trials is 10,000: 0.6676
#Probability when the number of trials is 100000: 0.66585
Again, you can clearly see that it is better to choose a door that is not the first choice. It's strange (´ ・ ω ・ `)
Recommended Posts