Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
TimWolla opened this issue Sep 15, 2023 · 0 comments
Labels
Projects

Comments

@TimWolla
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
Version 2.0
  
To do
Development

No branches or pull requests

2 participants