我一直在对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;
}
}
我不断改变随机数的最大限制(例如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%的时间我得到了这个平均范围内的结果。我不认为我们可以称其为接近随机。
我该怎么做才能获得相对随机的数字。
class myRandom { int rnd; public int Next() { return rnd = ++rnd % int.MaxValue; } }
可以保证不会出现重复,直到所有正整数都被使用过为止。 - Zano