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

前端 未结 14 1198
遇见更好的自我
遇见更好的自我 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 14:59

    /* Inputs: 
     * min - GMP number or string: lower bound
     * max - GMP number or string: upper bound
     * limiter - GMP number or string: how much randomness to use.
     *  this value is quite obscure (see `gmp_random`, but the default
     *  supplies several hundred bits of randomness, 
     *  which is probably enough.
     * Output: A random number between min (inclusive) and max (exclusive).
    */
    function BigRandomNumber($min, $max, $limiter = 20) {
      $range = gmp_sub($max, $min);
      $random = gmp_random();
      $random = gmp_mod($random, $range);
      $random = gmp_add($min, $random);
      return $random;
    }
    

    This is just the classic formula rand_range($min, $max) = $min + rand() % ($max - $min) translated to arbitrary-precision arithmetic. It can exhibit a certain amount of bias if $max - $min isn't a power of two, but if the number of bits of randomness is high enough compared to the size of $max - $min the bias becomes negligible.

提交回复
热议问题