News for hackers. Stuff that matters.
Re:Game Show Problem (1990) by StefanKarpinski on Saturday September 14, 2013 @05:44PM (#6387178)
I really only understood the Monty Hall Problem intuitively when I sat down to write a simulation of it to convince someone else that the math (which had already convinced me) was actually correct. Here's Julia code for it:

    function monty_hall(switch::Bool; n=3)
      winner, guess = rand(1:n), rand(1:n)
      reveal = setdiff(1:n,[winner,guess])[rand(1:end)]
      if switch
        guess = setdiff(1:n,[guess,reveal])[rand(1:end)]
      end
      return guess == winner
    end
This allows you to simulate the switch and don't switch strategies:

    julia> mean([ monty_hall(false) for _=1:100000 ])
    0.33166

    julia> mean([ monty_hall(true) for _=1:100000 ])
    0.6676
But more importantly, you can see that in the don't-switch case, the reveal choice is dead code – it has no effect on wether the original guess was right or not. That's the key insight: since the original guess had 1/3 chance of being right before the reveal, it still has a 1/3 change of being right after the reveal. Before the reveal the other two choices also each had a 1/3 chance of being winners, but after the reveal their combined 2/3 chance is concentrated entirely on the door that wasn't revealed, making that the best option.

The code also lets us see what happens with a generalized Monty Hall problem for more doors:

    julia> mean([ monty_hall(false, n=4) for _=1:100000 ])
    0.24862

    julia> mean([ monty_hall(true, n=4) for _=1:100000 ])
    0.37462

    julia> mean([ monty_hall(false, n=5) for _=1:100000 ])
    0.19763

    julia> mean([ monty_hall(true, n=5) for _=1:100000 ])
    0.2666
Even for higher numbers of doors, it's better to switch.

There are no comments on this comment yet.