Problems with rand() when tossing coin

5 views (last 30 days)
Jørgen
Jørgen on 7 May 2014
Edited: Jørgen on 8 May 2014
Im doing an assignment that is about cointossing, and when i do large amounts of tosses, it seems that the ratio between heads and tails aint 1.0000000. When I've added another random int generator, and tried to make a test to check if the results i get is plausible. It is the following:
format long;
m=1000000000; %Number of coin-tosses
[krone mynt ]=deal(0);
for i=1:m
resultat=myntkast;
if (resultat==1) %If heads
krone=krone+1;
else %If tails
mynt=mynt+1;
end
end
generator1=krone/mynt
[krone2 mynt2]=deal(0);
x=randi([0 1], 1,m);
for i=1:m
if (x(1,i)==0)
krone2=krone2+1;
else
mynt2=mynt2+1;
end
end
generator2=krone2/mynt2
%P(more Heads than krone, if p=0.5)
cumprob1=1-binocdf(krone,m,0.5);
%P(more Heads than krone2 if p=0.5)
cumprob2=1-binocdf(krone2,m,0.5);
Does this look right to you? Myntkast is still:
function resultat = myntkast
resultat=rand<0.5;
end
Regards Jørgen

Answers (1)

José-Luis
José-Luis on 7 May 2014
Simplifying your code a bit:
vals = rand(1000,1)>0.5;
ratio = sum(vals)/sum(~vals);
What makes you thing the results are "too far away". It is after all a random process.
Also, please note the rand() produces values in the [0,1[ interval. If you wanted the intervals for heads/tails to be the same you should do instead:
vals = rand(1000,1) >= 0.5;
But the impact of that would be extremely limited.
  3 Comments
José-Luis
José-Luis on 7 May 2014
Edited: José-Luis on 7 May 2014
That would be true if you were really sampling from a random distribution. If you are using a computer then the process is pseudo-random. What this means, among other things, is that, depending on the quality of the algorithm, after many samples, patterns start to emerge. That could affect your results, potentially introducing bias.
You are however nowhere near for that to happen with the default generator in Matlab (Mersenne-Twister).
Did your professors actually test this, considering the random number generator, or do they "think" it's wrong. Statistically speaking, you could calculate the p value and show the confidence in your results.
Jørgen
Jørgen on 7 May 2014
They "thought" it would be wrong, they did not test it. Thanks for the feedback, I'll try to use other random number generators and see if I get the same result. One professor asked if i could do the same in Python and compare the results, so I'll maybe do that.

Sign in to comment.

Categories

Find more on Random Number Generation in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!