rand() 如何从单个种子生成随机数序列?

How does rand() generate a sequence of random numbers from a single seed?

在一个循环中,设置一次种子就足以获得一系列随机数。函数 rand 如何仅基于一个种子生成大量随机数?

您所需要的只是一种将一个数字转换为两个数字的算法。一个数字成为你的下一个输出,另一个成为你的下一个种子。这样的算法非常简单。例如,您可以将数字乘以两个不同的素数,然后将每个素数减去 mod 65536。这将从单个输入产生两个输出。

另一种方法更简单:

1) 通过将种子乘以一个数字并添加第二个数字来置换种子。 (例如,seed = seed * 214013 + 2531011;。)

2) 只输出新种子的一部分。 (例如,return (seed >> 16) &0x7ffff;。)

实际上Pseudorandom, the numbers appear random but are not, they are deterministic since they can be predicted by the algorithm. A truly random number cannot be predicted. Using the same seed will produce the same sequence. The standard specifies and algorithm, but the actual algorithm使用取决于实现。