Monty Hall Skeptics
For Monty Hall Skeptics (who are also computer literate), here is Java code that executes the Monty Hall problem:
Results of 1,000,000 tests:
Stay Pat: you win 33.3166% of the time.
Switch: you win 66.6835% of the time.
Code:
import java.text.*; public class MontyHall { static void main(String[] args) throws java.io.IOException { System.out.println("Starting simulation"); NumberFormat percent = NumberFormat.getPercentInstance(); percent.setMinimumFractionDigits(6); int stayPatStrategy = 0; int switchStrategy = 0; // for simplicity, we always pick door one, but we randomly assign the caddy so it doesn't matter. for (int i = 0; ; ++i) { // pick caddy int caddy = getRandomNumberInRange(1,3); // see what would have happened had we stayed pat if (caddy == 1) { stayPatStrategy++; } // Monty picks a different door with a goat // to make it fair, we will pick randomly int goatDoor = getRandomNumberInRange(2,3); if (caddy == goatDoor) { goatDoor = (goatDoor == 2) ? 3 : 2; // set to other door if caddy } int remainingDoor = (goatDoor == 2) ? 3 : 2; // set to other door // we pick the remaining door. Is it the caddy? if (caddy == remainingDoor) { switchStrategy++; } // every so often, print results if ((i % 10000) == 0) { System.out.println(); System.out.println("Stay Pat = " + percent.format(stayPatStrategy/(double)i)); System.out.println("Switch = " + percent.format(switchStrategy/(double)i)); System.out.println("Total iterations: " + i); } } } static int getRandomNumberInRange(int start, int end) { double value = Math.random(); // 0 <= x < 1 return (int)((value * (end-start+1)) + start); // truncates } }
![]()