Skip to content

Core\Random\Seeded::float

$seeded->float(): float

Returns a float from a seeded generator. The result is at least 0 and less than 1.

You make the generator with new Core\Random\Seeded(42). The number 42 is the seed. Two generators with the same seed return the same floats in the same order, on every run. This makes a simulation repeatable: you can run it again and get the same result. The result can be 0.0, but it is never 1.0. Multiply it by 10, and the result is at least 0 and less than 10.

Good to know: anybody who knows the seed knows every value. When nobody may guess the value, use Core\Random::float.

Return value

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

Examples

The same seed gives the same floats

<?nvs
// Shows that two generators with the same seed return the same floats.
Core\Random\Seeded $first = new Core\Random\Seeded(42);
Core\Random\Seeded $second = new Core\Random\Seeded(42);
// Both lines are the same on every run.
echo $first->float(), ' ', $first->float(), ' ', $first->float(), "\n";
echo $second->float(), ' ', $second->float(), ' ', $second->float(), "\n";
Output
0.74156487877182 0.15991039287692 0.27860113025514
0.74156487877182 0.15991039287692 0.27860113025514

Always below one

<?nvs
// Shows that every result is at least 0 and less than 1.
Core\Random\Seeded $generator = new Core\Random\Seeded(7);
uint $outside = 0;
float $highest = 0.0;
uint $i = 0;
while ($i < 100000) {
float $value = $generator->float();
if ($value < 0.0 || $value >= 1.0) {
$outside = $outside + 1;
}
if ($value > $highest) {
$highest = $value;
}
$i = $i + 1;
}
// No result is outside the range. This prints 0.
echo $outside, "\n";
// The highest result is close to 1, but below it. This prints "yes".
echo $highest > 0.99 && $highest < 1.0 ? 'yes' : 'no', "\n";
Output
0
yes

A simulation you can repeat

<?nvs
// Shows how to simulate a server where one request in ten fails, with a result you can repeat.
// A request fails when its float is below 0.1. The seed is fixed, so the
// simulation counts the same failures every time it runs.
Core\Random\Seeded $generator = new Core\Random\Seeded(2024);
uint $failed = 0;
uint $longestRun = 0;
uint $run = 0;
uint $request = 0;
while ($request < 10000) {
if ($generator->float() < 0.1) {
$failed = $failed + 1;
$run = $run + 1;
if ($run > $longestRun) {
$longestRun = $run;
}
} else {
$run = 0;
}
$request = $request + 1;
}
// About 1000 of the 10000 requests fail.
echo 'failed: ', $failed, " of 10000\n";
echo 'most failures in a row: ', $longestRun, "\n";
Output
failed: 1060 of 10000
most failures in a row: 4