FakerPHP / Faker

Faker is a PHP library that generates fake data for you
https://fakerphp.github.io
Other
3.57k stars 345 forks source link

The Miscellaneous::boolean() generator could take a random float instead of an integer #761

Open TimWolla opened 1 year ago

TimWolla commented 1 year ago

Summary

Contrary to what I said in #760, it is safely possible to generate random floats between 0 and 1 (not including 1) in userland for 64 bit systems, by using the following construction:

random_int(0, (1 << 53) - 1) / (1 << 53)

(which is equivalent to PHP 8.3's Randomizer::nextFloat() or Randomizer::getFloat(0, 1))

This can be leveraged to generate a boolean with a specific non-integer chance as follows:

$bool = (random_int(0, (1 << 53) - 1) / (1 << 53)) < $chanceOfTrue;

See also the example in the corresponding PHP RFC: https://wiki.php.net/rfc/randomizer_additions#nextfloat