dimanche 1 novembre 2015

Generating discrete uniform distribution in C

I'm trying to generate a discrete uniform distribution in C between 0 and 1.

Normally you'd expect: t = rand()%2 , but it seems there is a problem with this approach (it seems to be related to lower bits having more probabilities, although I don't really understand much about that).

I tried a trick that I found somewhere on the Internet:

Let t1,t2 be 2 not so uniform distributions between 0 and 1 with probability p for 1, (1-p) for p. Then we take 2 random numbers:

t1 : p for 1, (1-p) for 0

t2 : p for 1, (1-p) for 0

If t1!=t2 we have the probability for (t1,t2)=(1,0) and (t1,t2) = (0,1) to be the same: p(1-p). So we just the repeat the sampling until we get t1!=t2 and we choose the random number t = t1 (it really doesn't matter). Here is my code:

#include <time.h>
#include <stdlib.h>


int main()
{
/*
Declare variable to hold seconds on clock.
*/
int i,t1,t2,t;
time_t seconds;
seconds = time(NULL);

/*
Get value from system clock and
place in seconds variable.
*/
time(&seconds);
/*
Convert seconds to a unsigned
integer.
*/
srand((unsigned int) seconds);
/*
Output random values.
*/
    for (i =0; i < 10; ++i)
    {
        do
        {
            t1 = rand()%2;
            t2 = rand()%2;
        }
        while (t1==t2);
        t = t1;

        printf("%d\n",t);
    }
            /*printf("%d",rand()%2);
    printf("%d",rand()%2);*/

return 0;
}

Am I right or wrong? Thank you very much!




Aucun commentaire:

Enregistrer un commentaire