在PHP中,如何生成一个大的伪随机数? [英] In PHP, how do I generate a big pseudo-random number?
问题描述
我正在寻找一种使用PHP生成 big 随机数的方法,例如:
I'm looking for a way to generate a big random number with PHP, something like:
mt_rand($lower, $upper);
我看得更近的是 gmp_random ( ),但是它不允许我仅指定每条肢的位数(我不知道这是什么)的上下边界.
The closer I've seen is gmp_random() however it doesn't allow me to specify the lower and upper boundaries only the number of bits per limb (which I've no idea what it is).
Axsuuls的答案似乎非常接近我想要的答案,并且与gmp_random非常相似,但是在一种情况下似乎只有一个缺陷.
假设我不会在以下之间获得随机数:
Suppose I wan't to get a random number between:
- 1225468798745475454898898465154
和:
- 1225468798745475454898898465200
因此,如果该函数名为 BigRandomNumber ():
So if the function is called BigRandomNumber():
BigRandomNumber($length = 31);
这可以轻松返回超出指定边界的9999999999999999999999999999999.
This can easily return 9999999999999999999999999999999 which is out of the specified boundary.
如何使用最小/最大边界而不是长度值?
BigRandomNumber('1225468798745475454898787465154', '1225468798745475454898787465200');
这应该返回一个介于 1225468798745475454898898465 [154 .. 200] 之间的随机数.
This should return a random number between 1225468798745475454898787465 [154 .. 200].
For the reference I believe the solution might have to make use of the function supplied in this question.
以上帖子已删除,这里是:
The above post was deleted, here it is:
function compare($number1, $operator, $number2) {
$x = bccomp($number1, $number2);
switch($operator) {
case '<':
return -1===$x;
case '>':
return 1===$x;
case '=':
case '==':
case '===':
return 0===$x;
case '!=':
case '!==':
case '<>':
return 0!==$x;
}
}
推荐答案
尝试以下操作:
function BigRandomNumber($min, $max) {
$difference = bcadd(bcsub($max,$min),1);
$rand_percent = bcdiv(mt_rand(), mt_getrandmax(), 8); // 0 - 1.0
return bcadd($min, bcmul($difference, $rand_percent, 8), 0);
}
数学公式如下:将最小值和最大值之间的差乘以随机百分比,然后加上最小值(四舍五入为整数).
The math is as following: multiply the difference between the minimum and maximum by a random percentage, and add to the minimum (with rounding to an int).
这篇关于在PHP中,如何生成一个大的伪随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!