c - 为什么这段代码要调用 rand() 两次才能获得至少 N 个随机位?

标签 c random

Programming Pearls 第 12 章中的第一个问题如下:

The C library rand() function typically returns about fifteen random bits. Use that function to implement a function bigrand() to return at least 30 random bits...

这是作者给出的解决方案:

int bigrand()
{
    return RAND_MAX*rand() + rand(); // why add the rand() in the last 
}

为什么作者在乘法之后添加对 rand 的调用?

最佳答案

如果没有额外的 rand(),结果将是 RAND_MAX 的倍数,因此甚至不是模糊的随机。

事实上,您显示的代码不太正确,它应该是

int bigrand()
{
    return (RAND_MAX+1)*rand() + rand(); // why add the rand() in the last 
}
对于某些 x,

RAND_MAX 几乎总是 2^x-1。如果没有 +1 ,则 RAND_MAX*rand()rand() 之间存在重叠,因此您实际上是添加了两个随机数,这会扭曲随机性(例如,将两个骰子 throw 加在一起)。

添加额外的 1 使其成为 2 的幂,因此 RAND_MAX*rand() 的底部 x 位全为 0;附加的 rand() 填充底部位。这更像是向左移动第一个 rand() 并在第二个中进行 or-ing。

请注意,此方法仅适用于生成一些非关键测试数据,但如果需要真正的线性随机性,则不应使用;如果您需要 30 位,您应该使用真正的 30 位(或更多)随机数生成器。

关于c - 为什么这段代码要调用 rand() 两次才能获得至少 N 个随机位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23946527/

相关文章:

python - 为什么这个 python 程序不工作?属性错误 : 'module' object has no attribute

c - Mersenne Twister init_by_array() 函数说明

在 "perf"事件处捕获用户空间变量

c - 在文件解析中使用 fgets()

c# - PInvoke 使堆栈不平衡

python-3.x - 如何在Python3中随机生成未观察到的数据

C - strncpy 用法 - 段错误

c - C 中的 Pow() 函数

c - 从 .txt 文件中读取随机行

C - 随机数生成