vendredi 18 décembre 2020

MONTY HALL SIMULATION: Why are these 2 versions of my code giving different output?

Before showing two different versions for my simulation of the Monty Hall problem:

+If this is the first time you heard about the Monty Hall problem before, you can find it here: https://www.youtube.com/watch?fbclid=IwAR35Ar6wrCtU-kxvqhFEvYm1ERhqI24iSzz5nZOwXfhBF1iPZn6ZlNaO1Vw&v=iBdjqtR2iK4&feature=youtu.be

or

https://en.wikipedia.org/wiki/Monty_Hall_problem

The Monty Hall problem is a famous conundrum in probability which takes the form of a hypothetical game show. The contestant is presented with three doors; behind one is a car and behind each of the other two is a goat. The contestant picks a door and then the gameshow host opens a different door to reveal a goat. The host knows which door conceals the car. The contestant is then invited to switch to the other closed door or stick with their initial choice.

Perhaps counter-intuitively, the best strategy for winning the car is to switch, as demonstrated by the following simulation.

+Here is a correct sample code of simulating the problem: https://matthew-brett.github.io/dsfe/chapters/extra/monty_hall_lists

So, I wrote 2 different versions of my own to simulate the problem.

The output of my program is the number of times the contestant won a car when they choose to switch for every case.

The first version, which gives the right output (~67):

import random
count = 0
n = 100
##n is number of test case
i = 0
while i<n:
  list1 = ["goat","goat","goat"]
  prize = random.randint(0,2)
  list1[prize] = "Car"
  choose = random.randint(0,2)
  while True:
    opendoor = random.randint(0,2)
    if (opendoor!=choose and list1[opendoor]!="Car"):
      break
  i+=1
  choose = 3- opendoor - choose
  if list1[choose]=="Car":
    count+=1
print(count)

The second version, which gives the wrong output (~50):

import random
count = 0
n = 100
##n is number of test case
i = 0
while i<n:
  list1 = ["goat","goat","goat"]
  prize = random.randint(0,2)
  list1[prize] = "Car"
  choose = random.randint(0,2)
  while True:
    opendoor = random.randint(0,2)
    if (opendoor!=choose):
      break
  if (list1[opendoor]!="Car"):
    i+=1
    choose=3-opendoor-choose
    if list1[choose]=="Car":
      count+=1
print(count)

Basically, they generate the same amount of loop, and all the numbers are also randomly generated. But I don't understand why the outputs are so different.

I know that the second program would eliminate all the cases where list1[open]=="Car". However, it still generates a new loop. I know that it could affect the result. The answer that I am looking for is a mathematical explanation of this problem.

So, once again. Can you please mathematically or logically explain why this occurs?




Aucun commentaire:

Enregistrer un commentaire