我想在C语言中生成0到1之间的离散均匀分布。
通常你会期望使用:t = rand()%2,但是这种方法存在问题(似乎更低位有更高的概率,尽管我不太理解这个问题)。
我试了一个在互联网上找到的技巧:
让t1、t2成为介于0和1之间的两个不很均匀的分布,其中1的概率为p,(1-p)的概率为p。然后我们取两个随机数:
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;
}
我是正确还是错误?非常感谢!
rand
到底出了什么问题,才能明白为什么这不可能起作用(与分布无关),但基本上:不要使用rand
。 - user2357112rand()%2
且不会因低熵位而导致偏差的简单方法是rand() > RAND_MAX / 2
。 - Cornstalks