(PHP 8 >= 8.3.0)
Random\Randomizer::nextFloat — Get a float between 0 and 1
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 uniformly selected float from the half-open interval [0, 1). Zero is a possible return value, one is not.
Random\Randomizer::$engine.
Example #1 Random\Randomizer::nextFloat() example
<?php
$r = new \Random\Randomizer();
// The resulting bool will be true with the given chance.
$chance = 0.5;
$bool = $r->nextFloat() < $chance;
echo ($bool ? "You won" : "You lost"), "\n";
?>The above example will output something similar to:
You won
Example #2 Incorrect scaling using an affine transformation
<?php
final class MaxEngine implements Random\Engine {
public function generate(): string {
return "\xff";
}
}
$randomizer = new \Random\Randomizer(new MaxEngine);
$min = 3.5;
$max = 4.5;
// DO NOT DO THIS:
//
// This will output 4.5, despite nextFloat() sampling from
// a right-open interval, which will never return 1.
printf("Wrong scaling: %.17g", $randomizer->nextFloat() * ($max - $min) + $min);
// Correct:
// $randomizer->getFloat($min, $max, \Random\IntervalBoundary::ClosedOpen);
?>The above example will output:
float(4.5)