In PHP, how do I generate a big pseudo-random number?

前端 未结 14 1145
遇见更好的自我
遇见更好的自我 2020-12-03 14:12

I\'m looking for a way to generate a big random number with PHP, something like:

mt_rand($lower, $upper);

The closer I\'ve

相关标签:
14条回答
  • 2020-12-03 15:16

    Big Integers are from 1-20 range. So generate a number using mt_rand($lower, $upper) and multiply with another mt_rand($lower, $upper)

    $N1=mt_rand($lower, $upper);
    $N2=mt_rand($lower, $upper);
    $N3=$N1*N2;
    

    Note:multiplication of n-digits with n-digits gives you n*2 digits.

    0 讨论(0)
  • 2020-12-03 15:17

    Try the following:

    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).

    0 讨论(0)
提交回复
热议问题