在 PHP 中,如何生成一个大的伪随机数?

2021-12-21 00:00:00 random php gmp bcmath

我正在寻找一种使用 PHP 生成大随机数的方法,例如:

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:

  • 1225468798745475454898787465154

和:

  • 1225468798745475454898787465200

所以如果函数被调用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');

这应该返回 1225468798745475454898787465 [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).

相关文章