An elegant way to return random float between two numbers:
<?php
function random_float ($min,$max) {
return ($min+lcg_value()*(abs($max-$min)));
}
?>
(PHP 4, PHP 5, PHP 7, PHP 8)
lcg_value — Combined linear congruential generator
lcg_value() returns a pseudo random number in the range of (0, 1). The function combines two CGs with periods of 2^31 - 85 and 2^31 - 249. The period of this function is equal to the product of both primes.
This function does not generate cryptographically secure values, and must not be used for cryptographic purposes, or purposes that require returned values to be unguessable.
If cryptographically secure randomness is required, the Random\Randomizer may be used with the Random\Engine\Secure engine. For simple use cases, the random_int() and random_bytes() functions provide a convenient and secure API that is backed by the operating system’s CSPRNG.
Scaling the return value to a different interval using multiplication or addition (a so-called affine transformation) might result in a bias in the resulting value as floats are not equally dense across the number line. As not all values can be exactly represented by a float, the result of the affine transformation might also result in values outside of the requested interval.
Use Random\Randomizer::getFloat() to generate a random float within an arbitrary interval. Use Random\Randomizer::getInt() to generate a random integer within an arbitrary interval.
This function has no parameters.
A pseudo random float value between 0.0 and 1.0, inclusive.
An elegant way to return random float between two numbers:
<?php
function random_float ($min,$max) {
return ($min+lcg_value()*(abs($max-$min)));
}
?>
Choose your weapon:
<?php
function mt_randf($min, $max)
{
return $min + abs($max - $min) * mt_rand(0, mt_getrandmax())/mt_getrandmax();
}
function lcg_randf($min, $max)
{
return $min + lcg_value() * abs($max - $min);
}
function randf($min, $max)
{
return $min + rand(0,getrandmax()) / getrandmax() * abs($max - $min);
}?>