Rand or mt_rand, that's the question..
| From: | Jani Taskinen | Date: | Thu, 02 Aug 2001 17:59:13 +0000 |
| Subject: | Rand or mt_rand, that's the question.. | ||
| References: | 1 | Groups: | php.dev |
| Request: | Send a blank email to php-dev+get-61865@lists.php.net to get a copy of this message | ||
I asked this last week, and I asked it long time ago too,
and for some reason nobody bothered even answering..
Why don't we just forget about using the system provided
randomness functions but use the 'Mersenne Twister' funcs
provided in ext/standard/rand.c ???
According to this manual page:
http://www.php.net/manual/en/function.mt-rand.php
It would be:
a) faster
b) works the same on any system
Or are there some reasons why NOT to use it on some cases?
If nobody objects, I will change this.
--Jani
On 2 Aug 2001 sulka@sulake.com wrote:
>From: sulka@sulake.com
>Operating system: Solaris (most unices)
>PHP version: 4.0.6
>PHP Bug Type: Arrays related
>Bug description: Shuffle shouldn't use the least significant bit of rand()
>
>In ext/standard/array.c, the sorting algorithm of shuffle
>is defined as
>
>(php_rand() % 2) ? 1 : -1
>
>This is fine for rand algorithms in which all bits are
>random but with Solaris and other unices this is not so.
>Quoting man random():
>
>"The difference is that rand(3C) produces a much less
>random sequence-in fact, the low dozen bits generated by
>rand go through a cyclic pattern. All the bits generated by
>random() are usable."
>
>This is not true however - the LSB of random() calls are
>predictable on some systems.
>
>You can verify if your system is affected by running this:
>
><?PHP
>$a = array();
>$b = array();
>
>for($i=0; $i<1000; $i++) // iterate 1000 times
> {
> $foo = "";
> // initialize random seq with new seed
> srand ($i);
> // create a string with the LSB of first 24 random numbers
> for($j=0; $j<24; $j++) {
> $c = rand();
> // $c = rand(0,32000); works on all systems
> // store the random number so we can check how many
>different
> // numbers were really generated
> $b[$c]= 1;
> // append the least signicant bit to the string
> $foo .= ($c % 2);
> }
> // store the parity string
> $a[$foo]= 1;
> }
>
>echo "Parity string count: " . count($a), "<BR>";
>echo "Random number count: " . count($b), "<BR>";
>?>
>
>If the counts are 1000/24000 you're fine. Affected systems
>I've tried this on return 4/24000.
>
>Proposed fix: change shuffle to call PHP's own rand
>function with limits, ie, rand(0,32000). This introduces
>randomness into the LSB and fixes shuffle.
>
>