So I've always found the Monty Hall problem interesting, because it's so counter-intuitive. Basically, you're given three doors, with a car behind one and a goat behind the other two. You pick one door and then the host opens one of the doors you haven't picked to reveal a goat, and then asks you if you want to switch. Intuitively, you'd think that you'd gain no advantage from switching, because either way you have a 1 in 3 chance of getting it right... right? But no, as vos Savant first showed, the actual probability of a hit is higher if you choose to switch. Significantly higher. I'd heard this of course, and seen the Bayes math to show it's true. But nonetheless, it's just so counter-intuitive that it's hard to believe.
Enter computer science! Python, as with many things, makes it a snap to whip up a Monty Hall simulation. Then run it a hundred thousand times and voila, we have our answer: and sure enough, 2/3 of the time, switching gave us the car, while only 1/3 of the time did staying with our first pick result in a hit. It's still hard to understand why... but the sim is pretty solid.
Here's the code:
http://pastebin.com/2KueJkf4
Here's a rendering of the pseudocode inside the montyPick function, the only non-trivial part of the simulation.
Given a randomized list of three doors:
Pick the first door
- if you chose the car, Monty opens one of the other two doors (both goats).
- if you chose a goat, Monty opens the other goat.
- set remainingDoor to be the one you haven't picked and Monty hasn't opened.
- if your initial choice was a hit, add 1 to the count of hits from staying. (this step could be done earlier if wanted)
- if the remainingDoor is a hit, add 1 to the count of hits from switching.
The outer loop just iterates this and shuffles the list, so each time you're getting a randomized list. I had initially randomized both the list itself and the pick, but I realized that was unneccessary and added unneeded code complexity as well as extending the runtime (though perhaps I could have eliminated this with some optimization).
And the results speak for themselves:
Out of 100000 trials run:
Trials won by switching: 66575 percent of total: 66.575
Trials won by staying: 33425 percent of total: 33.425
Tough to argue with! : )
No comments:
Post a Comment