I'm looking for a way to generate a big random number with PHP, something like:
mt_rand($lower, $upper);
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).
EDIT: Axsuuls answer seems to be pretty close to what I want and very similar to gmp_random however there seems to be only one flaw in one scenario.
Suppose I wan't to get a random number between:
and:
So if the function is called BigRandomNumber():
BigRandomNumber($length = 31);
This can easily return 9999999999999999999999999999999 which is out of the specified boundary.
How can I use a min / max boundary instead of a length value?
BigRandomNumber('1225468798745475454898787465154', '1225468798745475454898787465200');
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.
EDIT: 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;
}
}
An early computer-based PRNG, suggested by John von Neumann in 1946, is known as the middle-square method. The algorithm is as follows: take any number, square it, remove the middle digits of the resulting number as the "random number", then use that number as the seed for the next iteration.
The rand() function generates a random integer. Example tip: If you want a random integer between 10 and 100 (inclusive), use rand (10,100). Tip: As of PHP 7.1, the rand() function has been an alias of the mt_rand() function.
rand() or mt_rand() functions can be used to Generate 5 Digit Random Number in PHP.
Generate 4 Digit Random Number using mt_rand() mt_rand() function is just like rand() function but it is 4 times faster than rand() function. To use mt_rand() function define min and max numbers. The mt_rand() function will return a random integer between min and max numbers (including min and max numbers).
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With