monte carlo simulation question

1 view (last 30 days)
can anyone help me figure out whats wrong with this code. im trying to run a simulation where 3 people flip a coin if all are heads or tais they take them back. however if two coins come up heads or tails the person with the unique coin wins a coin from the other two. my problem is that my code doest follow the given conditions based on the code and instead only executes the first if statement.
a=5 % person 1 int coin
b=5 % person 2 int coin
c=5 % person 3 int coin
d=0
step=0
for i=1:1:100000
t=rand() % person 1 flip
y=rand() % person 2 flip
z=rand() % person 3 flip
a=a+d
b=b+d
c=c+d
while ( (a>0 && b>0) || (b>0&& c>0)||(a>0 && c>0) || (b>0&& a>0) ||(c>0&& a>0)||(c>0&& b>0) )
step=step+1
t=rand() % person 1 flip
y=rand() % person 2 flip
z=rand() % person 3 flip
if y&&t < .5
a= a -1
b= b-1
c= c+2
elseif y&&t >.5
a= a -1
b= b-1
c= c+2
elseif z&&t < .5
a= a -1
b= b+2
c= c-1
elseif z&&t >.5
a= a -1
b= b+2
c= c-1
elseif y&&z < .5
a= a +2
b= b-1
c= c-1
elseif y&&z >.5
a= a +2
b= b-1
c= c-1
elseif z&&t&&y >.5
a=a+0
b=b+0
c=c+0
elseif z&&t&&y <.5
a=a+0
b=b+0
c=c+0
end
a=a+0
b=b+0
c=c+0
end
end
disp(a)
disp(b)
disp(c)
disp(i)

Accepted Answer

Walter Roberson
Walter Roberson on 8 Nov 2011
Why are you flipping at the level of the "for i" loop, and then flipping again right the top of the "while" loop, without having tested the outcome of the flips?
Your code can be made simpler by using round(rand()) rather than rand(), as then you would have 0 and 1 values rather than values anywhere in the range [2^(-53) to 1-2^(-53)]
Your termination condition for the "while" loop contains redundancies. For example a>0 && c>0 is the same condition as (c>0&& a>0). And really all that you are testing there is that at least two people still have non-zero scores, which would be much more easily tested as ((a>0)+(b>0)+(c>0)) >= 2 . But I have to ask: why do you continue the game when someone goes broke?
What point does "d" have in the code? You initialize it to 0 and never change it.
After the change to 0/1 values, use abc as a vector of the scores, then your code for any one "experiment" reduces down to
abc = [5 5 5];
i = 0;
while all(abc) && i <= 10000
i = i + 1;
xyz = logical(round(rand(1,3)));
if all(xyz) || ~any(xyz)
%"give the money back" by not changing scores
else
xyz = xor(xyz, sum(xyz)==1);
abc(xyz) = abc(xyz) - 1;
abc(~xyz) = abc(~xyz) + 2;
end
end
disp([abc,i])
  2 Comments
Dr. Seis
Dr. Seis on 8 Nov 2011
Shouldn't the end sum of "abc" be the same as the beginning sum of "abc" ?
Should work if you change the line:
abc(~xyz) = abc(~xyz) + 1;
to:
abc(~xyz) = abc(~xyz) + 2;
Walter Roberson
Walter Roberson on 8 Nov 2011
Good point. I made the appropriate edit.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!