Create discrete uniform distribution in C

I am trying to create a discrete uniform distribution in C between 0 and 1.

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

I tried the trick I found somewhere on the Internet:

Let t1, t2 be equal to 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 that (t1, t2) = (1,0) and (t1, t2) = (0,1) will be the same: p (1-p). Therefore, we simply repeat the sampling until we get t1! = T2, and we choose a random number t = t1 (it really does not 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!

+4
2

rand(). random() , PCG.

. random() 31 . . 30. .

static inline int random_bit(void)
{
    static long val;
    static int bits = 0;
    int bit;

    if (bits == 0) {
        val = random();
        bits = 31;
    }
    bit = val & 1;
    val >>= 1;
    bits--;
    return bit;
}
+2

rand() , ( "p" "1-p" ). rand() > RAND_MAX / 2 , . , .

, , 1 0 "p" "1-p" , , , 2*p*(1-p) 1 0, , .

0

Source: https://habr.com/ru/post/1614090/


All Articles