首页 技术 正文
技术 2022年11月17日
0 收藏 397 点赞 4,077 浏览 1678 个字

GitHub: https://github.com/storagezhang

Emai: debugzhang@163.com

华为云社区: https://bbs.huaweicloud.com/blogs/249894

LevelDB: https://github.com/google/leveldb

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 为随机数种子,称 rand 生成的随机数为伪随机数,一个伪随机数常用的原则就是 M 尽可能的大。

在 LevelDB 的随机数类 Random 类中,\(A=16807, M=2147483647, C=0\):

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 位除法。

下面证明 \(product\ \%\ M = (product >> 31) + (product\ \&\ M)\):

\[\begin{align}

&将\ product\ 分为高\ 33\ 位和低\ 31\ 位 \\
\\
&令高\ 33\ 位的值为\ H,低\ 31\ 位的值为\ L \\
\\
&则\ product = H << 31 + L = H \cdot 2^{31}+L = H \cdot M + L \\
\\
&因为\ product = seed \cdot A, 且\ seed\ 和\ A\ 都小于\ M,故\ H\ 必小于\ M \\
\\
&等式左边 = product \%\ M = (H \cdot M+L) \%\ M = (H + L) \%\ M \\
\\
&等式右边 = (product >> 31) + (product\ \&\ M) = (H \cdot 2^{31}+L)>>31 + L = H + L \\
\end{align}
\]

此时考虑下方的 if 语句:

if (seed_ > M) {
seed_ -= M;
}

由于 \(H\) 和 \(L\) 都小于 \(M\),故 \(H+M<2L\)。

经过语句,等式右边也等于 \((H + L) \%\ M\) 了。

综上,等式成立

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,077
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,552
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,400
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,176
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,813
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,896