Created
April 20, 2011 03:19
-
-
Save jcchurch/930274 to your computer and use it in GitHub Desktop.
Monty Hall Problem solved with Monte Carlo Simulations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* The Monty Hall Problem is a famous teaching problem | |
* in statistics. It works like this: | |
* | |
* Imagine that you are on the show "Let's Make a Deal" | |
* with Monty Hall. Monty shows you three doors and says | |
* that a car exists behind one of them. You may pick | |
* one door and if the car is behind it, you win the car. | |
* | |
* You pick a door. Monty then chances the rules. He opens | |
* a different door and shows you that there was a goat | |
* behind it. Good thing you didn't pick that door! | |
* Monty gives you the opportunity to change to the other | |
* unopened door. | |
* | |
* Which is better? Stick with your current door or to move | |
* your choice to the other unopened door? Does this even | |
* matter? There are now just two unopened doors. It should | |
* be a 50-50 shot, right? | |
* | |
* Turns out it isn't. It take a little bit of thought to | |
* determine why this is, but we can simulate the results | |
* with a million iterations of someone who never changes | |
* their choice and someone who always changes their choice. | |
* | |
* You'll have to run the program to see the results. | |
*/ | |
import java.io.*; | |
import java.util.*; | |
public class monty { | |
public static void main(String[] args) { | |
Random rng = new Random(); | |
int trials = 1000000; | |
System.out.println("Player never changes the door."); | |
int wins = 0; | |
for (int i = 1; i <= trials; i++) { | |
int prize_door = rng.nextInt(3); | |
int contestant_door = rng.nextInt(3); | |
if (contestant_door == prize_door) | |
wins++; | |
} | |
System.out.println("Total Wins out of "+trials+": "+wins); | |
System.out.println("Percent win: "+(double)wins/trials); | |
System.out.println(""); | |
System.out.println("Player always changes the door."); | |
wins = 0; | |
for (int i = 1; i <= trials; i++) { | |
int prize_door = rng.nextInt(3); | |
int contestant_door = rng.nextInt(3); | |
// Here, we randomly look for doors until | |
// we find one that that is wrong, yet still | |
// wasn't picked by the contestant. | |
int wrong_door = prize_door; | |
while (wrong_door == prize_door || | |
wrong_door == contestant_door) { | |
wrong_door = rng.nextInt(3); | |
} | |
int alternate_door = 3 - (contestant_door + wrong_door); | |
// Always switch doors! | |
if (alternate_door == prize_door) | |
wins++; | |
} | |
System.out.println("Total Wins out of "+trials+": "+wins); | |
System.out.println("Percent win: "+ (double)wins/trials); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment