Re: ext-random: add random_float() ?
| From: | Tim Düsterhus | Date: | Thu, 29 Dec 2022 13:25:00 +0000 |
| Subject: | Re: ext-random: add random_float() ? | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-119213@lists.php.net to get a copy of this message | ||
Hi
On 12/20/22 07:27, Go Kudo wrote:
Now that my work is done, I was thinking about a proposal for a sunsetting of existing functions for PHP 8.3 based on the features introduced in ext-random, and I realized that there is no alternative toI'm not convinced that a random_float() function is a good addition. Especially not with the proposed behavior: 1. Using the (0, 1, ClosedClosed) behavior does neither match Randomizer::nextFloat(), nor Randomizer::getFloat(). 2. I consider the ClosedOpen behavior to be the "correct" default, because the interval can then be cleanly split into equally sized subintervals. -------------------- But even when random_float() would work like Randomizer::nextFloat() (i.e. (0, 1, ClosedOpen)), I would not consider this a good addition: Users would likely attempt to scale the returned value to arbitrary ranges using thelcg_value(). Essentially, this could be completely replaced by Random\Randomizer::getFloat(), but there are easierrandom_int()andrandom_bytes()functions for ints and strings. The Randomizer may be overkill and complicated for PHP use cases where random number reproducibility is not required in many cases. So, why not add arandom_float(): floatfunction? This function, like the others, uses CSPRNG and returns a value between 0.0 and 1.0. This behavior isClosedClosed. Opinions are welcome.
($min + random_float() * ($max - $min)) construction, instead of using Randomizer::getFloat().
As per Drawing Random Floating-Point Numbers from an Interval. Frédéric Goualard, ACM Trans. Model. Comput. Simul., 32:3, 2022 this construction is unsafe, because is is both biased and also may return values outside the expected interval.
--------------------
So random_float() would rather need to behave like Randomizer::getFloat() instead of Randomizer::nextFloat() and then it would not be much simpler than using the Randomizer class directly. I further expect that needing to generate random floats is much rarer than needing to generate random integers or random bytes (for tokens), thus having convenience functions for those two, but not floats is acceptable and keeps the API surface simple, making it easier to document all the gotchas. Users can add convenience wrappers themselves.
Best regards
Tim Düsterhus