note 39690 added to function.rand
| From: | raz0 at rn2 dot php dot net | Date: | Sat, 07 Feb 2004 16:32:56 +0000 |
| Subject: | note 39690 added to function.rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-64782@lists.php.net to get a copy of this message | ||
If you need a way to select a random number between 1 and X and need 1 to be the number most likely
to be selected and X to be the least likely, well .. here is the solution. :)
<?php
function randomNumber($max, $exp)
{
$maxValue = pow($max, $exp);
srand((double)microtime()*1234567);
$rand = rand(1, $maxValue);
for($i=1; $i<=$max; $i++)
{
$values[$i] = pow($i, $exp);
}
$count = count($values);
$number = $max;
for($i=1; $i<=$count; $i++)
{
if ($rand <= $values[$i])
{
return $number;
}
$number--;
}
}
?>
Description: int randomNumber ( int max, float exp)
Example: $value = randomNumber(10, 2)
This will select a number between 1 and 10, where 10 is rather unlikely.
You can use the code below to test this function. It's rather messy, but who cares - It works.
;)
<?php
$array = array("", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
for ($i=0; $i<=30000; $i++)
{
$array[randomNumber(10, 1.5)]++;
}
$sum = array_sum($array);
unset($array[0]);
foreach ($array as $number => $entry)
{
print "$number - " . ((int) ($entry*100/$sum)) . "%\n";
}
?>
----
Manual Page -- http://www.php.net/manual/en/function.rand.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+39690
Delete -- http://master.php.net/manage/user-notes.php?action=delete+39690&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+39690&report=yes
Search -- http://master.php.net/manage/user-notes.php