使用 rand5() 生成 rand7()(具有相同的概率)

本文关键字:概率 rand7 rand5 生成 使用 | 更新日期: 2023-09-27 18:33:14

可能的重复项:
将随机范围从 1–5 扩展到 1–7

我在这里看到了这个问题:链接

作者提供的解决方案似乎没有产生相同的概率。

例如,在对该函数的 10k 次调用中,数字 4 返回了 1-2 次(当其他数字(如 2)分别返回大约 2k 次时)。

也许我理解错了,

或者我写错了算法,但在这里:

    static int rand5()
    {
        return new Random().Next(1, 6);
    }
    static int rand7()
    {
        while (true)
        {
            int num = 5 * (rand5() - 1) + rand5();
            if (num < 22) return ((num % 7) + 1);
        }
    }
    static void Main(string[] args)
    {
        int limit = 10000;
        int[] scores = new int[7];
        for (int i = 0; i < limit; i++)
        {
            scores[rand7() - 1]++;
        }
        foreach (int n in scores)
        {
            Console.Write(n + " ");
        }
        Console.WriteLine();
    }

提前谢谢。

使用 rand5() 生成 rand7()(具有相同的概率)

你不是在 Rand5 中生成随机数。

这样做:

static Random rand = new Random()
static int rand5()
{
    return rand.Next(1, 6);
}