【发布时间】:2010-02-25 14:47:07
【问题描述】:
我一直在对 Random 类进行一些测试,并使用了以下代码:
while (x++ <= 5000000)
{
y = rnd.Next(1, 5000000);
if (!data.Contains(y))
data.Add(y);
else
{
Console.WriteLine("Cycle {2}: Repetation found for number {0} after {1} iteration", y, x, i);
break;
}
}
我不断更改 rnd 最大限制(即 5000000)并更改了迭代次数,得到以下结果:
1) if y = rnd.Next(1, 5000) : The average is between 80 to 110 iterations
2) if y = rnd.Next(1, 5000000) : The average is between 2000 to 4000 iterations
3) if y = rnd.Next(1, int.MaxValue) : The average is between 40,000 to 80,000 iterations.
为什么我会得到这些平均值,即在我检查每个值的 10 次中,有 80% 的时间都在这个平均值范围内。我不认为我们可以称它为随机。
我该怎么做才能得到一个相当随机的数字。
【问题讨论】:
-
它被称为伪随机是有原因的。
-
随机并不意味着“独特”。
-
恭喜你发现了生日悖论。 (en.wikipedia.org/wiki/Birthday_problem)
-
9, 9, 9, 9 你确定这是随机的吗?这就是随机的问题,你永远无法确定。
-
根据你对随机的定义,考虑使用类似
class myRandom { int rnd; public int Next() { return rnd = ++rnd % int.MaxValue; } }Guaranteed noncyclic,直到所有正整数都用完为止。
标签: c# random birthday-paradox