note 105265 added to function.array-rand
| From: | Sebmil at osu1 dot php dot net | Date: | Fri, 05 Aug 2011 19:18:24 +0000 |
| Subject: | note 105265 added to function.array-rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-182269@lists.php.net to get a copy of this message | ||
Looks like this function has a strange randomness.
If you take any number of elements in an array which has 40..100 elements, the 31st one is always by
far the less occuring (by about 10% less than others).
I tried this piece of code at home (PHP Version 5.3.2-1ubuntu4.9) and on my server (PHP Version
5.2.17), unfortunately i haven't any server with the last version here :
<?php
$valeurs = range(1, 40);
$proba = array_fill(1, 40, 0);
for ($i = 0; $i < 10000; ++$i)
{
$tirage_tab = array_rand($valeurs, 10);
foreach($tirage_tab as $key => $value)
{
$proba[$valeurs[$value]]++;
}
}
asort($proba);
echo "Proba : <br/>\n";
foreach($proba as $key => $value)
{
echo "$key : $value<br/>\n";
}
?>
In every try, the number of occurrences change a bit but the 31 is always far less (around 2200)
than the others (2400-2600). I tried with 50 and 100 elements, no change. I tried with more or less
elements to pick (second parameter to array_rand), same result. If you pick only one element
it's even worse : 31 has half the result of the others.
For this particular case, i recommend shuffling the array and taking the nth first elements, in this
test it's 60% faster and the statistics are ok.
----
Server IP: 69.147.83.197
Probable Submitter: 88.165.96.36
----
Manual Page -- http://www.php.net/manual/en/function.array-rand.php
Edit -- https://master.php.net/note/edit/105265
Del: integrated -- https://master.php.net/note/delete/105265/integrated
Del: useless -- https://master.php.net/note/delete/105265/useless
Del: bad code -- https://master.php.net/note/delete/105265/bad+code
Del: spam -- https://master.php.net/note/delete/105265/spam
Del: non-english -- https://master.php.net/note/delete/105265/non-english
Del: in docs -- https://master.php.net/note/delete/105265/in+docs
Del: other reasons-- https://master.php.net/note/delete/105265
Reject -- https://master.php.net/note/reject/105265
Search -- https://master.php.net/manage/user-notes.php