c - 在 C 中生成离散均匀分布

标签 c random

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

通常你会期望: t = rand()%2 ,但这种方法似乎有问题(它似乎与低位有更多概率有关,虽然我对此不太了解).

我尝试了一个在 Internet 某处找到的技巧:

设 t1,t2 是 0 和 1 之间的 2 个不太均匀的分布,1 的概率为 p,p 的概率为 (1-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;
}

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

最佳答案

切勿使用 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;
}

关于c - 在 C 中生成离散均匀分布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33470471/

相关文章:

python - 如何在Python中像正常情况一样在两个值之间生成随机Beta?

c++ - 地震 2 md2 文件格式(理论)

python - 从pyfits数据表中获取随机子样本

javascript - 与 Math.random 的 v-bind 行为不符合预期

python - 如何在 python 中使用 ctypes 重载 C 库的弱声明函数?

matlab - matlab中randn函数的问题

javascript - 容器内元素的随机位置

c - 二进制 char 数组的补码

c - 静态变量的奇怪情况仅出现在 gcc 的调试版本中

c - 我的 C 代码无法运行