Register a domain and help support LQ
 Home Forums HCL Reviews Tutorials Articles Register Search Today's Posts Mark Forums Read
 LinuxQuestions.org Simulating the "Monty Hall Problem"

Notices

Rate this Entry

# Simulating the "Monty Hall Problem"

Posted 05-18-2011 at 05:43 AM by D1ver
Updated 05-26-2011 at 09:20 PM by D1ver

I was reading about the "Monty Hall Problem" this afternoon and in an attempt to simulate it I wrote some code. The following should run in Matlab / GNU Octave. Results agree with the theory.
Code:
```%	Code to simulate the monty hall problem
%	The array 'doors' represent the 3 doors
%	Door States:
%	0 - uninitialized
%	1 - car
%	2 - goat
%	3 - revealed
%
%	Neil Dick
%

% clear everything..
clc
clear all
close all

%Initialize
numOfSimulatedGames = 100000;
numGamesPlayed = 0;
successfulSwitch = 0;
probabilityOfSuccess=zeros(1,numOfSimulatedGames);
for numGamesPlayed = 1:numOfSimulatedGames
doors = zeros(1,3);

% Stick a car behind a random door
rNum = 3*rand();
if( (rNum>0) && (rNum<1))
doors(1) = 1;
elseif( (rNum>1) && (rNum<2))
doors(2) = 1;
else
doors(3) = 1;
end
% Fill in the other 2 spots with goats..
for i = 1:3
if(doors(i)==0)
doors(i) = 2;
end
end
% Have contestant randomly pick a door.
rNum = 3*rand();
if( (rNum>0) && (rNum<1))
chosenDoor = 1;
elseif( (rNum>1) && (rNum<2))
chosenDoor = 2;
else
chosenDoor = 3;
end

% Reveal the first goat door that isnt a chosen door.
picked = 0;
for i = 1:3
if(i~=chosenDoor)
if(doors(i)~=1)
if(picked==0)
%door isn't a car, isn't the one the contestant picked, and we havent revealed yet..
doors(i)=3;
picked =1;
end
end
end
end
% At this point the theory says it's beneficial to switch your choice.
% so, if the door that (hasn't been picked or revealed) is the car, increment
% a variable and calculate the probabiltiy.
for i = 1:3
if(i~=chosenDoor)
if(doors(i)~=3)
%Not chosen or revealed, must be the door we'd switch too..
if(doors(i)==1)
%If we would have switched and won the car
successfulSwitch = successfulSwitch+1;
end
end
end
end
probabilityOfSuccess(numGamesPlayed) = successfulSwitch / numGamesPlayed;
end
xaxis = 1:numGamesPlayed;
figure
plot(xaxis,probabilityOfSuccess);
xlabel('Number of games played')
ylabel('Probability of a succesful switch')```
The results of running the code are shown in the image attached. The probability converges on 2/3 as expected. After some more grappling with the problem I think I finally understand the solution.

In the event that you pick a goat on the first selection, 'Monty' will eliminate the remaining goat, and you will always switch to a car. The chances of picking a goat on the first attempt are 2/3. So switching is actually the correct answer.
Attached Images
 result.jpg (20.2 KB, 16 views)
Posted in Uncategorized
« Prev     Main     Next »

All times are GMT -5. The time now is 04:06 PM.

 Contact Us - Advertising Info - Rules - LQ Merchandise - Donations - Contributing Member - LQ Sitemap -