[英]Mt_rand returns 0
mt_rand(~PHP_INT_MAX, PHP_INT_MAX);
Run a couple of times gives me the following output: 运行几次会给我以下输出:
php > echo mt_rand(~PHP_INT_MAX, PHP_INT_MAX) . PHP_EOL;
0
php > echo mt_rand(~PHP_INT_MAX, PHP_INT_MAX) . PHP_EOL;
0
php > echo mt_rand(~PHP_INT_MAX, PHP_INT_MAX) . PHP_EOL;
-3445259641993297920
php > echo mt_rand(~PHP_INT_MAX, PHP_INT_MAX) . PHP_EOL;
0
php > echo mt_rand(~PHP_INT_MAX, PHP_INT_MAX) . PHP_EOL;
0
php > echo mt_rand(~PHP_INT_MAX, PHP_INT_MAX) . PHP_EOL;
0
It does not seem very random. 似乎不是很随机。 Could anyone explain why it so often returns 0? 谁能解释为什么它经常返回0? I was expecting a "random" number between the lowest and highst available 我期望在最低和最高之间有一个“随机”数字
Even more, if you change it abit like 更重要的是,如果您将其更改为
echo mt_rand(-PHP_INT_MAX, PHP_INT_MAX)
It will start returning 1 instead of 0 它将开始返回1而不是0
It is always a good idea to read the manual when in doubt. 如有疑问,阅读本手册始终是一个好主意。
Caution The distribution of mt_rand() return values is biased towards even numbers on 64-bit builds of PHP when max is beyond 2^32. 注意当max超过2 ^ 32时,mt_rand()返回值的分布在64位版本的PHP上偏向偶数。 This is because if max is greater than the value returned by mt_getrandmax(), the output of the random number generator must be scaled up. 这是因为如果max大于mt_getrandmax()返回的值,则必须按比例放大随机数生成器的输出。
As mentioned in the comments by marcio the right solution would be 正如marcio的评论中所述,正确的解决方案是
mt_rand(-mt_getrandmax(), mt_getrandmax())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.