Edit report at https://bugs.php.net/bug.php?id=45184&edit=1
ID: 45184
Updated by: nikic@php.net
Reported by: kala at sankya dot com
Summary: algorithm to limit random numbers to a certain range
is flawed
-Status: Assigned
+Status: Closed
Type: Bug
Package: Math related
Operating System: *
PHP Version: 5.6.11
Assigned To: pajoye
Block user comment: N
Private report: N
New Comment:
This has been fixed in PHP 7.1.
Previous Comments:
------------------------------------------------------------------------
[2017-07-28 22:19:37] kala at sankya dot com
Since this bug hasn't been addressed even as of PHP version 7, looks very unlikely that it will
ever be fixed. Since the only way out is to implement your own function for unbiased scaling, here
is a replacement function that performs unbiased scaling :
function mt_rand_x($min,$max)
{
$range = $max - $min + 1;
$mt_max = mt_getrandmax()+1;
$limit = $mt_max-($mt_max % $range);
do
{
$rnd = mt_rand();
} while ($rnd >= $limit);
return ($rnd % $range)+$min;
}
Note : This is the replacement for the mt_rand($min,$max) function. For implementing an unbiased
replacement for the rand($min,$max) function, change the mt_rand() calls to rand() and the
mt_getrandmax() call to getrandmax().
------------------------------------------------------------------------
[2015-08-05 13:23:55] cmb@php.net
Indeed, as pointed out by the reporter, RANGE_RANDOM() is flawed.
The new CSPRNG function random_int() seems to get the scaling
right[1].
[1] <https://github.com/php/php-src/blob/php-7.0.0beta2/ext/standard/random.c#L184-L197>
------------------------------------------------------------------------
[2015-08-05 12:09:46] cmb@php.net
Related To: Bug #45301
------------------------------------------------------------------------
[2013-02-18 00:33:55] php-bugs at lists dot php dot net
No feedback was provided. The bug is being suspended because
we assume that you are no longer experiencing the problem.
If this is not the case and you are able to provide the
information that was requested earlier, please do so and
change the status of the bug back to "Open". Thank you.
------------------------------------------------------------------------
[2010-05-21 12:14:13] mike@php.net
Should probably be in feedback state.
------------------------------------------------------------------------
The remainder of the comments for this report are too long. To view
the rest of the comments, please view the bug report online at
https://bugs.php.net/bug.php?id=45184
--
Edit this bug report at https://bugs.php.net/bug.php?id=45184&edit=1