I\'m looking for a way to generate a big random number with PHP, something like:
mt_rand($lower, $upper);
The closer I\'ve
/* 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.