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 to `lcg_value()`.
Essentially, this could be completely replaced by
Random\Randomizer::getFloat(), but there are easier `random_int()` and
`random_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 a `random_float(): float` function? This function, like the
others, uses CSPRNG and returns a value between 0.0 and 1.0. This behavior
is `Closed` `Closed`.
Opinions are welcome.
I'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 the `($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
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php