1

我在 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 个部分:

  1. 第一个概率为 10% * 10 = 1
  2. 第二个概率为 20% * 10 = 2
  3. 第三个概率为 30% * 10 = 3
  4. 第四个概率为 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 函数返回的结果。我确定我犯了一个基本的数学错误,我怀疑在哪里,但我不知道如何解决它。

4

2 回答 2

3

确实是你!

在您的第二遍中,您每遍给它 60 个值,而不是 240 个,因此您将在该遍中获得大约四分之一的预期值。将每个运行到 240 并使用模 60 来获取您在每个循环中寻找的值的范围。

于 2009-05-11T03:20:54.740 回答
2

如果您期望DoIt_02()返回与 大致相同数量的结果DoIt_01(),那么是的,您犯了一个基本的数学错误。您部分的概率权重总和为 10 没有任何意义,因为加权机会不适用于整个 0..240 集。如果您在 0..240 而不是 0..59、60..119 等上运行每个受限概率,它将返回类似的结果。

顺便说一句,您的Chance()功能略有偏差,为了获得您似乎正在尝试的概率,它应该是mt_rand(1, $universe) <= $chanceor mt_rand(0, $universe - 1) < $chance

于 2009-05-11T03:18:19.893 回答