問題描述
偏見的定義是什么:
mt_rand() 返回值的分布在 64 位上偏向偶數當 max 超過 2^32 時構建 PHP.
The distribution of mt_rand() return values is biased towards even numbers on 64-bit builds of PHP when max is beyond 2^32.
如果這是四舍五入的替代平局規則中所述的那種偏見,我不'不要認為這真的很重要(因為偏差并不明顯).
If it's the kind of bias stated in alternate tie-breaking rules for rounding, I don't think it really matters (since the bias is not really visible).
除了 mt_rand()
被聲稱是四次比rand()
快,只需在前面加三個字符即可!
Besides mt_rand()
is claimed to be four times faster than rand()
, just by adding three chars in front!
假設 mt_rand
可用,使用它的缺點是什么?
Assuming mt_rand
is available, what's the disadvantage of using it?
推薦答案
mt_rand
使用 Mersenne Twister 算法,遠優于 LCGLCG代碼>rand.例如,LCG 的周期是微不足道的 232,而 mt_rand 的周期是 219937 ? 1.此外,LCG 生成的所有值將 躺在線上或平面繪制到多維空間中時.此外,確定LCG的參數不僅在實踐中可行,而且相對容易.LCG 的唯一優勢是速度可能稍快一些,但其規模與在 php 中編碼時完全無關.
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.
但是,mt_rand
也不適合用于加密目的(生成令牌、密碼或加密密鑰).
However, mt_rand
is not suitable for cryptographic purposes (generation of tokens, passwords or cryptographic keys) either.
如果您需要加密隨機性,請在 php 7 中使用 random_int
.在較舊的 php 上版本,在符合 POSIX 的操作系統上從 /dev/urandom
或 /dev/random
讀取.
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.
這篇關于mt_rand 的缺點是什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!