function BigInteger::randomRange
Generates a pseudo-random number between `$min` and `$max`.
Using the default random bytes generator, this method is suitable for cryptographic use.
@psalm-param (callable(int): string)|null $randomBytesGenerator
Parameters
BigNumber|int|float|string $min The lower bound. Must be convertible to a BigInteger.:
BigNumber|int|float|string $max The upper bound. Must be convertible to a BigInteger.:
callable|null $randomBytesGenerator A function that accepts a number of bytes as an integer,: and returns a string of random bytes of the given length. Defaults to the `random_bytes()` function.
Throws
MathException If one of the parameters cannot be converted to a BigInteger, or `$min` is greater than `$max`.
File
-
vendor/
brick/ math/ src/ BigInteger.php, line 255
Class
- BigInteger
- An arbitrary-size integer.
Namespace
Brick\MathCode
public static function randomRange(BigNumber|int|float|string $min, BigNumber|int|float|string $max, ?callable $randomBytesGenerator = null) : BigInteger {
$min = BigInteger::of($min);
$max = BigInteger::of($max);
if ($min->isGreaterThan($max)) {
throw new MathException('$min cannot be greater than $max.');
}
if ($min->isEqualTo($max)) {
return $min;
}
$diff = $max->minus($min);
$bitLength = $diff->getBitLength();
// try until the number is in range (50% to 100% chance of success)
do {
$randomNumber = self::randomBits($bitLength, $randomBytesGenerator);
} while ($randomNumber->isGreaterThan($diff));
return $randomNumber->plus($min);
}