我试图获得一些关于 C 中 rand()
的规范和实现的信息,但我找不到太多信息。事实上,除了:
- rand() 在函数调用之间不前进
- 相同的种子总是产生相同的数字
- 随机数介于 0 和
RAND_MAX
值得注意的是,这些都不需要随机性。具体来说,我没有看到任何禁止此实现的内容:
int randval = 0;
void srand(unsigned int seed) {
randval = seed;
return;
}
int rand() {
return randval++;
}
这似乎有点不随机。我是否缺少一些标准?
(另外,用 time() 播种 rand(),然后用 rand() 播种 ISAAC 不好吗?)
最佳答案
不仅不必是随机的,而且一定不能是随机的,因为它必须是完全确定的:
The srand function uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand. If srand is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated. If rand is called before any calls to srand have been made, the same sequence shall be generated as when srand is first called with a seed value of 1.
如果您需要真正的随机性——出于任何加密目的——在 Linux(和大多数其他 unices)和 CryptGenRandom 上使用 /dev/random
在 Windows 上。
如果您反而对伪随机 序列与随机序列的相似程度感兴趣,那就是它有多少 statistically random , 请参阅 @Story Teller's answer .
关于c - C 的 rand() 必须是随机的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43199526/