Coin flip issue

I'm trying to determine the probability of a coin flip. However my coin flip to determine the # of heads is not working out well. It only alternates between 0 and 1000. Can someone help? I'm out of ideas. Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

double coin ()
{
    double heads = 0;
    int count = 1;
    while (count <= 1000) //I'm running a simulation of 1000 times
    {
         int flip = static_cast<int>(10*MersenneTwister(0))%2;
if (flip == 1) //if flip outcome is a head
        {
        heads = heads + flip; //add it to # of heads
        count++; //increment count by 1
        }
        else
        {
            count++; //dont do anything besides increment count by one. 
        }
    }
    heads = heads/1.0;
    return heads;
}
Last edited on
(10*MersenneTwister(0))%2
What is MersenneTwister? What is 0 as parameter? What does it returns? I bet this line generates terribly skewed randomn nuber.

That was second hidden problem in your code.

First one is: why do you think it should generate anything but 0 or 1000? Your code states clearly: generate number flip, if it is one, add it to heads 1000 times. So only possible outcome is 0 or 1000.
MersenneTwister is a random number generator. You can find the code for it online, and it's pretty long, so I didn't include it here. I only want 0 and 1 as my possible random numbers, 0 for tails, 1 for heads.

It shoudl generate around 500, some more or less is alright, because after tossing 1000 times, it should average around 500 heads.
Is there something wrong with my loop?

Thanks!
Last edited on
Never mind, I got it!
because after tossing 1000 times
You toss it only once, then run loop one thousand times.

MersenneTwister is a random number generator
I am familiar with Mersenne Twister. In canonical form as devised by its creators, it generates a 32 bit sequence. Or, if you want, an unsigned int. As you feel the need to cast results to int, and after multiplying it by 10 and taking modulo 2 you sometimes get 1 (impossible if result of call is an integer), I think that MersenneTwister in fact is not a pure Mersenne Twister, and is something slightly different.
I also do not know why do you use own implementation of MT and are using bad way of generating a distribution instead of relying on correct implementation of MT in C++ Standard Library and using its proper distribution generators.
Topic archived. No new replies allowed.