Problems with rand() when tossing coin

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

답변 (1개)

José-Luis
José-Luis 2014년 5월 7일

0 개 추천

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

Jørgen
Jørgen 2014년 5월 7일
Only reason I have a serperate function is that i use it in a bigger program. I have talked to three of the professors at my university. All of them agree that when you do as many simulations as I do (100 000 000 coin tosses), the ratio really should be closer to 1 than i get with my simulations.
José-Luis
José-Luis 2014년 5월 7일
편집: José-Luis 2014년 5월 7일
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 2014년 5월 7일
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.

댓글을 달려면 로그인하십시오.

질문:

2014년 5월 7일

편집:

2014년 5월 8일

Community Treasure Hunt

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

Start Hunting!

Translated by