A random floating-point number is a value produced by a generator, with an unpredictable result and lacking any visible pattern. PHP offers a Randomizer
class to generate random values. Starting from PHP 8.3, this class includes new methods: nextFloat
and getFloat
. The nextFloat
method produces a random floating-point number within the range [0.0, 1.0)
. On the other hand, the getFloat
method generates a random floating-point number within specified minimum and maximum boundaries.
<?php
use Random\IntervalBoundary;
use Random\Randomizer;
$rnd = new Randomizer();
echo $rnd->nextFloat().PHP_EOL; // [0.0, 1.0)
echo $rnd->getFloat(0.5, 2.5).PHP_EOL; // [0.5, 2.5)
echo $rnd->getFloat(0.5, 2.5, IntervalBoundary::ClosedClosed).PHP_EOL; // [0.5, 2.5]
The getFloat
method takes an IntervalBoundary
as its third parameter to specify whether the minimum and maximum values should be inclusive or not.
IntervalBoundary::ClosedOpen
- minimum value may be included, maximum may not (default).IntervalBoundary::ClosedClosed
- both minimum and maximum values may be included.IntervalBoundary::OpenClosed
- minimum value may not be included, maximum may.IntervalBoundary::OpenOpen
- neither minimum nor maximum value may be included.
The nextFloat
method is essentially equivalent to getFloat(0, 1, IntervalBoundary::ClosedOpen)
. However, the internal implementation of nextFloat
is more efficient.
Leave a Comment
Cancel reply