【发布时间】:2012-10-17 19:27:15
【问题描述】:
我有一个数字列表
$list = array(1,5,19,23,59,51,24)
在实际代码中,这是从数据库生成的,因此该数组最多可容纳 500 个彼此不同的数字。
数据库中的每一个数字都有发生的概率记录。所以我有以前执行的数据来生成从 1 到 500 的随机数,并记录了每个数字生成 1000 次的概率。
现在有了每个数字的数字和概率列表,我想编写一个函数,根据它们的概率从这 500 个数字中生成一个随机数。
例如:
number 1 has a chance of: 0.00123 //0.123%
number 6 has a chance of: 0.0421 //4.21%
number 11 has a chance of: 0.0133 //1.33%
所以变量 $finallist 看起来像这样:
$finallist[1] = 0.00123;
$finallist[6] = 0.0421;
$finallist[11] = 0.0133;
现在,如果我运行我的函数并传入 $finallist 作为参数,我想检索 1 到 6 之间的随机数,但数字 6 出现的可能性高于 1,而 11 出现的可能性高于1.
我编写了一些函数来处理根据机会返回随机数,但它只需要 1 个值作为参数。
private function randomWithProbability($chance, $num, $range = false)
{
/* first generate a number 0 and 1 and see if that number is in the range of chance */
$rand = $this->getRandomFloatValue(0, 1);
if ($rand <= $chance)
{
/* the number should be returned */
return $num;
}
else
{
/* otherwise return a random number */
if ($range !== false)
{
/* make sure that this number is not same as the number for which we specified the chance */
$rand = mt_rand(1, $range);
while ($rand == $num)
{
$rand = mt_rand(1, $range);
}
return $rand;
}
}
}
如果有人知道执行此操作的解决方案/算法,或者 PHP 有什么内置的东西,那将是一个很大的帮助。非常感谢。
【问题讨论】:
-
我会让会说 PHP 的人写下答案(可以是你),但这里是大体思路。您要做的是创建一个包含累积分布的数组,即您的概率的总和。然后选择 rand 不超过累积分布的最大索引。
-
您的回答是有道理的,但同时也没有。我不明白选择最大索引会给我带来更高概率的随机数
-
"我想检索一个介于 1 和 6 之间的随机数,但是 ... 11 比 1 更有可能出现" 我认为您在这里要么有不需要的信息,要么您有错误...
标签: php algorithm random probability