C语言中伪随机数生成算法实际上是采用了"线性同余法"。具体的计算如下:
seed = (seed * A + C ) % M
其中A,C,M都是常数(一般会取质数)。当C=0时,叫做乘同余法。
假设我们定义随机数函数:
void rand(int &seed)
{
seed = (seed * A + C ) % M;
}
每次调用rand函数都会产生一个随机值赋值给seed,可以看出实际上用rand函数生成的是一个递推的序列,一切值都来源于最初的seed。所以当初始的seed取一样的时候,得到的序列都相同。
我们称seed为种子,一个伪随机数常用的原则就是M尽可能的大。例如,对于32位的机器来说,选择M=2^31-1=2147483647, A=7^5=16807时可以取得最佳效果。
现在我们来看看levelDB里随机数Random类是如何实现的:
在Random类中,A为16807,M为2147483647,C为0;
#ifndef STORAGE_LEVELDB_UTIL_RANDOM_H_
#define STORAGE_LEVELDB_UTIL_RANDOM_H_
#include <stdint.h>
namespace leveldb {
// A very simple random number generator. Not especially good at
// generating truly random bits, but good enough for our needs in this
// package.
class Random
{
private:
uint32_t seed_;
public:
// 0x7fffffffu == 2147483647L == 2^31-1 == 01111111 11111111 11111111 11111111
// 表达式s & 0x7fffffffu,确保结果值在[0,2147483647]范围内
explicit Random(uint32_t s) : seed_(s & 0x7fffffffu)
{
// Avoid bad seeds.
// seed_不能为零或M,否则所有的后续计算的值将为零或M
if (seed_ == 0 || seed_ == 2147483647L)
{
seed_ = 1;
}
}
// 16807随机数
uint32_t Next()
{
//01111111 11111111 11111111 11111111
static const uint32_t M = 2147483647L; // 2^31-1
//0100 0001 1010 0111
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]
// 这里将seed_*A设置为随机数生成器product,注意到product是64位的。
// 那么seed_=product % M就相当于得到大小在[1,M-1]之间的随机数。
uint64_t product = seed_ * A;
// Compute (product % M) using the fact that ((x << 31) % M) == x.
// 对于product % M,使用(product >> 31) + (product & M)进行运算优化,
// 考虑到右移和与操作的代价远小于取余操作。
// 下面等式用到了((x << 31) % M) == x的技巧(等式的证明见第三节)
// product%M == static_cast<uint32_t>((product >> 31) + (product & M))的证明见第四节
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_;
}
// Returns a uniformly distributed value in the range [0..n-1]
// 返回范围[0..n-1]内的均匀分布值。
// REQUIRES: n > 0
uint32_t Uniform(int n) { return Next() % n; }
// Randomly returns true ~"1/n" of the time, and false otherwise.
// REQUIRES: n > 0
bool OneIn(int n) { return (Next() % n) == 0; }
// Skewed: pick "base" uniformly from range [0,max_log] and then
// return "base" random bits. The effect is to pick a number in the
// range [0,2^max_log-1] with exponential bias towards smaller numbers.
// 偏态:Uniform(max_log + 1)取值范围是[0,max_log],1左移[0,max_log]得到
// 范围是[1,2^max_log],uniform([1,2^max_log])得到的范围是[0,2^max_log-1]
uint32_t Skewed(int max_log)
{
return Uniform(1 << Uniform(max_log + 1));
}
};
} // namespace leveldb
三.证明等式(x<<31)%M == x成立。其中M等于2^31-1
计算表达式左边(x << 31) % M,由于x<<31等于x*2^31,
则(x << 31) % M=(x*2^31)%M=(x + x*(2^31-1))%M=(x + x*M)%M=x
四.证明等式(product%M) == (product>>31)+(product&M),其中M等于2^31-1
因为product类型是uint64_t,可以将product从左到右分解成高33位和低31位,如下:
高33位 低31
(product>>31)<<31+product&M
(product>>31)<<31+product&M=(product>>31)*2^31+product&M=seed_*A,由于seed_和A都小于M,所以(product>>31)小于M
product%M = ((product>>31)<<31+product&M)%M
取模运算满足分配率(a+b)%c=(a%c+b%c)%c
product%M = ((product>>31)*2^31+product&M)%M
product%M = (((product>>31)<<31)%M+(product&M)%M)%M
根据第三节((product>>31)<<31)%M=(product>>31),先假设product&M小于M
product%M = (product>>31+product&M)%M
product%M = product>>31+product&M,先假设(product>>31+product&M)小于M。
但是低31位的值product&M可能等于M,这样就会导致product%M的值大于M的错误(肯定小于2M),不过源码中采取了如下安全措施。
seed_ = static_cast<uint32_t>((product >> 31) + (product & M));
if (seed_ > M)
{
seed_ -= M;
}