使用rand函数时发现,产生的随机数有相同的规律。查了一下才发现有真假随机数之分,好奇是什么导致了rand函数生成的是假随机数,而srand的是真随机数?
PHP中文网2017-04-17 11:39:28
The questioner seems to have mistaken the function of srand
. This function is used to set the seed of random numbers, not to generate random numbers. When the seed is determined, the value sequence generated by continuously calling rand
is determined, which is pseudo-random.
The so-called truly random, completely unpredictable random numbers generally require reading the white noise of some external devices to obtain the random numbers, such as the noise from the headphone input port or the noise from the network card interface. There is a /dev/random
in *nix system that is used to generate such true random numbers.
True randomness cannot be simulated by a fixed algorithm, because once a fixed algorithm is established, the random sequence can be predicted, and it is not truly random.
高洛峰2017-04-17 11:39:28
I just looked at the source code of php and found that your tag is C++. But it doesn’t matter, it’s pretty much the same.
rand
The function is a random number generating function, and this function is regular (you also discovered it).
srand
is the seeding function, which generates a seed for the random number generator, and then the rand
function generates random numbers based on this initialization seed.
As for the algorithm, most random number generators use the Linear Congruential Algorithm.
The following is the C++ code:
int __cdecl rand (
void
)
{
_ptiddata ptd = _getptd();
return( ((ptd->_holdrand = ptd->_holdrand * 214013L
+ 2531011L) >> 16) & 0x7fff );
}
The output is the result of removing the high 15
bit of the highest bit (the 32
bit integer is first shifted right by 16
bits, and then the low 15
bit is taken).
Reference: http://www.cplusplus.com/reference/random/
PHP中文网2017-04-17 11:39:28
srand is only used to set random seeds
http://zh.wikipedia.org/wiki/%E7%A1%AC%E4%BB%B6%E9%9A%8F%E6%9C%BA%E6%95%B0%E7%94% 9F%E6%88%90%E5%99%A8