2022年12月20日(火) 18:14 Go Kudo <g-k...@colopl.co.jp>:

> 2022年12月20日(火) 17:15 Hans Henrik Bergan <divinit...@gmail.com>:
>
>> btw while we're on the topic, does anyone know if this function gives
>> biased results/is-safe or not? i honestly don't know:
>> function random_float(float $min, float $max): float
>> {
>>     if ($min > $max) throw new \InvalidArgumentException("min must be
>> less than max");
>>     if ($min === $max) return $min;
>>     return $min + random_int(0, PHP_INT_MAX) / PHP_INT_MAX * ($max -
>> $min);
>> }
>>
>>
>> On Tue, 20 Dec 2022 at 09:06, Hans Henrik Bergan <divinit...@gmail.com>
>> wrote:
>> >
>> > >returns a value between 0.0 and 1.0.
>> >
>> > wouldn't it be better to follow random_int(int $min, int $max) design?
>> eg
>> > random_float(float $min, float $max): float
>> >
>> > On Tue, 20 Dec 2022 at 07:27, Go Kudo <g-k...@colopl.co.jp> wrote:
>> > >
>> > > Hi Internals.
>> > >
>> > > Congratulations on the release of PHP 8.2.
>> > > I just recently upgraded production PHP from 7.4 to 8.1 :)
>> > >
>> > > 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.
>> > >
>> > > Regards,
>> > > Go Kudo
>>
>
> Hi.
>
> The dangers of generating floating-point random numbers from PHP integer
> values are explained in detail in Tim and Joshua's RFC.
>
> https://wiki.php.net/rfc/randomizer_additions
>
> I missed it at first too, and was negative about adding
> `Randomizer::getFloat()` ...
> In general, I think this problem is less noticeable and the absence of the
> random_float() function increases the likelihood of incorrect
> implementations in userland.
>
> Regards,
> Go Kudo
>

In the PHP-8.3 current development branch, you can already polyfill as
follows However, it is complicated.

```php
<?php
function random_float(float $min = 0.0, float $max = 1.0,
\Random\IntervalBoundary $intervalBoundary =
\Random\IntervalBoundary::ClosedClosed): float {
    return (new \Random\Randomizer())->getFloat($min, $max,
$intervalBoundary);
}
```

Reply via email to