Skip to content

Core\Random::float

Core\Random::float(): float

Returns a random float that is at least 0 and less than 1.

Every value in that range is equally likely. The result can be 0.0, but it is never 1.0. This makes it easy to scale the result into your own range: multiply it by 10, and the result is at least 0 and less than 10. The number comes from the same cryptographic generator as every other Core\Random method.

Good to know: for a whole number in a range, such as a dice roll, use Core\Random::int. It gives an exact result, and you do not need to round anything.

Return value

Returns float. A float with 53 random bits. The result can be 0.0, but never 1.0.

Examples

Always below one

<?nvs
// Shows that `Core\Random::float` always returns a value from 0 up to, but not including, 1.
uint $inRange = 0;
uint $i = 0;
while ($i < 1000) {
float $value = Core\Random::float();
if ($value >= 0.0 && $value < 1.0) {
$inRange = $inRange + 1;
}
$i = $i + 1;
}
// Every one of the 1000 values is in the range. This prints 1000.
echo $inRange, "\n";
Output
1000

One time in ten

<?nvs
// Shows how to do something for about one request in ten, for example to log it.
uint $logged = 0;
uint $request = 0;
while ($request < 100000) {
// A value below 0.1 comes up one time in ten.
if (Core\Random::float() < 0.1) {
$logged = $logged + 1;
}
$request = $request + 1;
}
// The exact count changes on every run, but it is always close to 10000.
echo $logged > 9000 && $logged < 11000 ? 'about one in ten' : 'far from one in ten', "\n";
Output
about one in ten

Wait before a retry

<?nvs
// Shows how to add a random part to the wait before a retry. Clients that failed
// together then do not all retry at the same moment.
float $wait = 100.0;
uint $attempt = 1;
while ($attempt <= 4) {
// The wait is the base time plus up to half of it again.
float $withJitter = $wait + $wait * 0.5 * Core\Random::float();
// The random part changes on every run, so this prints the range the wait is in.
bool $inRange = $withJitter >= $wait && $withJitter < $wait * 1.5;
echo 'attempt ', $attempt, ': ', $inRange ? 'between ' . ($wait as string) . ' and ' . (($wait * 1.5) as string) . ' ms' : 'outside the range', "\n";
$wait = $wait * 2.0;
$attempt = $attempt + 1;
}
Output
attempt 1: between 100 and 150 ms
attempt 2: between 200 and 300 ms
attempt 3: between 400 and 600 ms
attempt 4: between 800 and 1200 ms