C 语言中伪随机数生成算法实际上是采用了"线性同余法":
其中 都是常数(一般会取质数)。当 时,叫做乘同余法。
假设定义随机数函数
void rand(int &seed)
{
seed = (seed * A + C ) % M;
}
每次调用 rand 函数都会产生一个随机值赋值给 seed,实际上 rand 函数生成的随机数是一个递推序列,初值为 seed。所以当初始的 seed 相同时,得到的递推序列也会相同。我们称 seed 为随机数种子,称 rand 生成的随机数为伪随机数,一个伪随机数常用的原则就是 M 尽可能的大。
在 LevelDB 的随机数类 Random 类中,:
explicit Random(uint32_t s) : seed_(s & 0x7fffffffu) {
// Avoid bad seeds.
if (seed_ == 0 || seed_ == 2147483647L) {
seed_ = 1;
}
}
uint32_t Next() {
static const uint32_t M = 2147483647L; // 2^31-1
static const uint64_t A = 16807; // bits 14, 8, 7, 5, 2, 1, 0
// We are computing
// seed_ = (seed_ * A) % M, where M = 2^31-1
//
// seed_ must not be zero or M, or else all subsequent computed values
// will be zero or M respectively. For all other values, seed_ will end
// up cycling through every number in [1,M-1]
uint64_t product = seed_ * A;
// Compute (product % M) using the fact that ((x << 31) % M) == x.
seed_ = static_cast<uint32_t>((product >> 31) + (product & M));
// The first reduction may overflow by 1 bit, so we may need to
// repeat. mod == M is not possible; using > allows the faster
// sign-bit-based test.
if (seed_ > M) {
seed_ -= M;
}
return seed_;
}
源码中利用 (product >> 31) + (product & M) 来代替 product % M,主要是为了避免 64 位除法。
下面证明 :
此时考虑下方的 if 语句:
if (seed_ > M) {
seed_ -= M;
}
由于 和 都小于 ,故 。
经过语句,等式右边也等于 了。
综上,等式成立
Emai: debugzhang@163.com
LevelDB: github.com/google/leve…