note 25344 added to function.rand
| From: | morthanpurpl at yahoo dot com | Date: | Fri, 20 Sep 2002 10:28:06 +0000 |
| Subject: | note 25344 added to function.rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-37025@lists.php.net to get a copy of this message | ||
On 16-Jul-2002 at 05:27, noisehnois@sigilodoemail.org.net wrote:
-----
$firsts = rand(0,999);
$seconds = rand(0,999);
$thirds = rand(0,999);
$fourths = rand(0,999);
$total = $firsts.$seconds.$thirds.$fourths;
echo $total;
-----
...which is ALMOST perfect. But not quite.
Simple concatenation will cause "clumps" in the distribution of the "random"
numbers.
Examples:
Given: $firsts = 123; $seconds = 45; $thirds = 6; $fourths = 789;
Then: $total = 123456789
Given: $firsts = 12; $seconds = 345; $thirds = 67; $fourths = 89;
Then: $total = 123456789
But fear not! sprintf to the rescue!
Given: $firsts = 123; $seconds = 45; $thirds = 6; $fourths = 789;
Then $total = sprintf("%03d%03d%03d%03d", $firsts, $seconds, $thirds, $fourths) =
123045006789;
Given: $firsts = 12; $seconds = 345; $thirds = 67; $fourths = 89;
Then $total = sprintf("%03d%03d%03d%03d", $firsts, $seconds, $thirds, $fourths) =
012345067089;
hApPY raNDomiZING!
--
http://www.php.net/manual/en/function.rand.php
http://master.php.net/manage/user-notes.php?action=edit+25344
http://master.php.net/manage/user-notes.php?action=delete+25344
http://master.php.net/manage/user-notes.php?action=reject+25344