使用rand5(),生成rand7()(概率相同) [英] Use rand5(), to generate rand7() (with the same probability)
本文介绍了使用rand5(),生成rand7()(概率相同)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
将随机范围从 1–5 扩展到 1–7
我在这里看到了这个问题:链接
I have seen the question in here: Link
作者提供的解决方案似乎没有产生相同的概率.
The solution the author provided didn't seem to generate the same probability.
例如,在对该函数的 10k 次调用中,数字 4 被返回了 1-2 次(而其他数字,如 2,每个都被返回了大约 2k 次).
For example, the number 4, out of 10k calls for the function, was returned 1-2 times (when the other numbers, like 2, were returned about 2k times each).
也许我理解错了,或者我写错了算法,但在这里:
Maybe I understood wrong, or I wrote the algorithm wrong, but here:
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 中生成随机数.
You are not generating random numbers in Rand5.
这样做:
static Random rand = new Random()
static int rand5()
{
return rand.Next(1, 6);
}
这篇关于使用rand5(),生成rand7()(概率相同)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文