What's the disadvantage of mt_rand?

后端 未结 2 1883
半阙折子戏
半阙折子戏 2020-11-27 17:51

What\'s the definition of bias in:

The distribution of mt_rand() return values is biased towards even numbers on 64-bit builds of PHP when max is beyo

2条回答
  •  北海茫月
    2020-11-27 18:06

    mt_rand uses the Mersenne Twister algorithm, which is far better than the LCG typically used by rand. For example, the period of an LCG is a measly 232, whereas the period of mt_rand is 219937 − 1. Also, all the values generated by an LCG will lie on lines or planes when plotted into a multidimensional space. Also, it is not only practically feasible, but relatively easy to determine the parameters of an LCG. The only advantage LCGs have is being potentially slightly faster, but on a scale that is completely irrelevant when coding in php.

    However, mt_rand is not suitable for cryptographic purposes (generation of tokens, passwords or cryptographic keys) either.

    If you need cryptographic randomness, use random_int in php 7. On older php versions, read from /dev/urandom or /dev/random on a POSIX-conforming operating system.

提交回复
热议问题