在C中生成离散均匀分布

时间:2015-11-02 03:51:40

标签: c random

我正试图在C和0之间生成一个离散的均匀分布。

通常你会期望:t = rand()%2,但似乎这种方法存在问题(它似乎与具有更多概率的低位相关,尽管我对此并不太了解)。

我尝试了一种在互联网上找到的技巧:

令t1,t2为2,在0和1之间不是那么均匀的分布,概率p为1,(1-p)为p。然后我们取2个随机数:

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

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

如果t1!= t2,则(t1,t2)=(1,0)和(t1,t2)=(0,1)的概率相同:p(1-p)。所以我们只重复采样,直到得到t1!= t2,然后我们选择随机数t = t1(这没关系)。这是我的代码:

#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;
}

我是对还是错?非常感谢你!

2 个答案:

答案 0 :(得分:2)

永远不要使用rand()。使用random()甚至更好,generator from the PCG family

对于任何一个,所有提供的位都是好的。 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;
}

答案 1 :(得分:0)

内置随机数生成器rand()不能保证具有您所假设的特定分布('p'和'1-p'的概率)。虽然rand() > RAND_MAX / 2更好,但它仍然可能没有特定的分布。最好使用here所述的任何其他方法。

话虽如此,如果你假设你的随机数生成器的概率为1和0都是'p'和'1-p',那么你所做的生成均匀分布的方法看起来在数学上是正确的,概率为{{ 1}}对于1和0中的每一个,尽管你不愿意像你在评论中指出的那样使用它。