目前我对 stdlib 中 rand() 函数中用于生成随机数的线性同余生成器有点困惑。 https://en.wikipedia.org/wiki/Linear_congruential_generator 上的表列出了 GCC 和 ANSI C 使用的模数为 2^31。然而,根据 https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf p347,对于 ANSI C 2^32 是隐式使用的。 stdlib 中的 rand() 也使用 2^32 吗?
我已经实现并测试了 ANSI C 实现,效果很好。
在 Glibc 中,
rand
(在 rand.c 中定义)。
只是 __random
的包装。 __random
(在random.c中定义)只是__random_r
的包装。而__random_r
(在random_r.c中定义)有两个不同的代码路径,但我认为相关的是这个:
int32_t val = ((state[0] * 1103515245U) + 12345U) & 0x7fffffff;
state[0] = val;
*result = val;