我在 PHP 中有以下代码可以正常工作(每次运行时返回或多或少 10 个结果):
function GetAboutTenRandomNumbers()
{
$result = array();
for ($i = 0; $i < 240; $i++)
{
if (Chance(10, 240) === true)
{
$result[] = $i;
}
}
echo '<pre>';
print_r($result);
echo '</pre>';
return $result;
}
Chance() 函数如下:
function Chance($chance, $universe = 100)
{
$chance = abs(intval($chance));
$universe = abs(intval($universe));
if (mt_rand(1, $universe) <= $chance)
{
return true;
}
return false;
}
现在,我想将这 10 个(平均)结果随机分成以下 4 个部分:
- 第一个概率为 10% * 10 = 1
- 第二个概率为 20% * 10 = 2
- 第三个概率为 30% * 10 = 3
- 第四个概率为 40% * 10 = 4
如您所见,所有段的总和 (1 + 2 + 3 + 4) 等于 10,因此我编写了以下函数来执行此操作。
function GetAboutTenWeightedRandomNumbers()
{
$result = array();
// Chance * 10%
for ($i = 0; $i < 60; $i++)
{
if (Chance(10 * 0.1, 240) === true)
{
$result[] = $i;
}
}
// Chance * 20%
for ($i = 60; $i < 120; $i++)
{
if (Chance(10 * 0.2, 240) === true)
{
$result[] = $i;
}
}
// Chance * 30%
for ($i = 120; $i < 180; $i++)
{
if (Chance(10 * 0.3, 240) === true)
{
$result[] = $i;
}
}
// Chance * 40%
for ($i = 180; $i < 240; $i++)
{
if (Chance(10 * 0.4, 240) === true)
{
$result[] = $i;
}
}
echo '<pre>';
print_r($result);
echo '</pre>';
return $result;
}
问题是我已经运行了几十次 GetAboutTenWeightedRandomNumbers 函数,结果远低于 GetAboutTenRandomNumbers 函数返回的结果。我确定我犯了一个基本的数学错误,我怀疑在哪里,但我不知道如何解决它。