实现随机数发生器 [英] Implementation of random number generator
问题描述
可能重复:
随机数生成器如何工作?
我正在寻找一个随机数生成器在C / C ++的内部实现。基本上我有兴趣知道,当rand()被调用时究竟发生了什么。在所有机器遵循一定的指令集后,如何随机!
编辑:想知道如何在C / C ++中实现一个。
I am looking for internal implementation of a random number generator in C/C++.Basically I am interested to know, what exactly happens when rand() is called. After all machine follows definite set of instructions, how can it be random!
Want to know how can I implement one in C/C++.
推荐答案
它们是伪随机数字生成器,而不是真正随机的。这通常是一个好的的东西,因为它允许你在涉及随机数字时更容易地再现错误。
They're pseudo-random number generators, not truly random ones. This is often a good thing since it allows you to reproduce bugs more easily where "random" numbers are involved.
获得随机数生成器,例如在Linux下读取 / dev / random
,但是通常不包含C库附带的常规生成器。
You can get random number generators, such as reading /dev/random
under Linux but the normal ones that ship with C libraries generally aren't.
最简单的是线性同余发生器,其中:
The simplest one are linear congruential generators where:
n(x+1) = n(x) * A + C modulo M
< A , C
和 M
。
LCG上的维基百科页面提供了各种实施所使用的一些示例值。例如,列出的 glibc
有 a = 1103515245,c = 12345,m = 2 ^ 31
一个简单的事情像:
Wikipedia's page on LCGs gives some sample values used by various implementations. For example, the glibc
one listed there has a = 1103515245, c = 12345, m = 2^31
so it's a simple thing like:
static unsigned int seed = 1;
void srand (int newseed) {
seed = (unsigned)newseed & 0x7fffffffU;
}
int rand (void) {
seed = (seed * 1103515245U + 12345U) & 0x7fffffffU;
return (int)seed;
}
Aside:glibc实现仍然有这个生成器在它内部(称为类型0生成器),但它也有一个fancier三重发生器,也是(可能)更好。
Aside: The glibc implementation still has this generator within it (called the Type 0 generator) but it also has a fancier trinomial generator as well, which is (presumably) better.
还有更复杂的(例如Mersenne捻线机)具有更大的周期时间(开始重复之前的时间)。
There are also more complex ones (such as the Mersenne twister) that have a much greater cycle time (time before starting to repeat).
任何真正的随机生成器必须使用真正的随机输入源,这是为什么 / dev / random
有时会阻塞(等待熵)而 / dev / urandom
不会。
Any truly random generator must use a truly random input source which is why /dev/random
will sometimes block ("waiting for entropy") while /dev/urandom
won't.
真正的随机源可能受按键,uers所需的数据,网络数据包内容,磁盘I / O模式,ICMP响应在网络上返回所需的时间以及各种其他令人惊奇的,主要是非显性的事情。
"Truly" random sources may be affected by timing between keystrokes, data enetered by uers, the contents of network packets, disk I/O patterns, time taken for an ICMP response to come back over the network and all sorts of other wondrous, mostly non-deteministic things.
除非你大量加入加密,正常随机数发生器将很好。
Unless you're heavily into crypto, normal random number generators will be just fine.
这篇关于实现随机数发生器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!