note 116469 added to function.array-rand

From: Date: Thu, 08 Jan 2015 01:21:42 +0000
Subject: note 116469 added to function.array-rand
Groups: php.notes 
Request: Send a blank email to php-notes+get-201382@lists.php.net to get a copy of this message
@Sebmil : You say this function "has a strange randomness [, because] the 31st one is always by far the less occuring (by about 10% less than others)." That's right (at least under linux, PHP 5.3). And it's also visible when calling array_rand with 1 as second parameter. After checking the code, and testing it, I concluded that you have to call srand() at each iteration of your loop. To be simple, a rand() call is made <n> times when the <n>th key is returned; I suppose there is a flaw in the pseudorandom number generator (PRNG) that php uses; somehow the generation has a frequency of 31 (when a random number is sufficiently low, then the 31st after it will be more higher). Reinitializing the PRNG each time you enter the loop make the problem disappear (and is cheaper, in terms of time, than using shuffle). In other words, the following code : for ($i = 0; $i < 10000; ++$i) { /* reinitialize the PRNG --> */ srand(); $tirage_tab = array_rand($valeurs, 10); foreach($tirage_tab as $key => $value) { $proba[$valeurs[$value]]++; } } doesn't have the strange behaviour you noticed. No PRNG is perfectly random, so taking the habit of calling srand() from time to time is still a good practice if you rely on a lot of random numbers. ---- Server IP: 72.52.91.14 Probable Submitter: 2a01:e35:2f2b:10e0:d5a9:e274:71d0:99b3 ---- Manual Page -- http://php.net/manual/en/function.array-rand.php Edit -- https://master.php.net/note/edit/116469 Del: integrated -- https://master.php.net/note/delete/116469/integrated Del: useless -- https://master.php.net/note/delete/116469/useless Del: bad code -- https://master.php.net/note/delete/116469/bad+code Del: spam -- https://master.php.net/note/delete/116469/spam Del: non-english -- https://master.php.net/note/delete/116469/non-english Del: in docs -- https://master.php.net/note/delete/116469/in+docs Del: other reasons-- https://master.php.net/note/delete/116469 Reject -- https://master.php.net/note/reject/116469 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#201382) next »