Thanks to visit codestin.com
Credit goes to github.com

Skip to content

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

@TimWolla

Description

@TimWolla

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions