为什么Random()不是随机的? [英] Why isn't Random() random?
问题描述
可能重复:
为什么此随机数生成器不是随机的?
我有这个测试程序:
static void Main(string[] args)
{
var randomNumbers = new Dictionary<int, int>();
foreach (var s in Enumerable.Range(1, 500))
{
var rand = Rand5();
if (!randomNumbers.ContainsKey(rand))
randomNumbers.Add(rand, 1);
else
randomNumbers[rand] += 1;
}
randomNumbers
.ToList()
.ForEach(x => Console.WriteLine("{0}: {1}", x.Key, x.Value));
Console.ReadLine();
}
static int Rand5()
{
System.Threading.Thread.Sleep(1);
return new Random().Next(1, 6);
}
如果我将System.Threading.Thread.Sleep(1);
注释掉,我将得到
5: 500
但是,如果我取消注释该行,则会得到随机数.
2: 87
4: 94
1: 116
5: 108
3: 95
为什么代码行很重要?谢谢!
正如其他人所说,new Random()
从当前系统时间播种随机数生成器.
我有一篇文章对此进行了更详细的描述,包括解决问题的方法,您可能会发现这很有用.基本上,您想多次使用相同的Random
实例-但要注意,它不是线程安全的.
Possible Duplicate:
Why does this Random Number Generator not random?
I have this test program:
static void Main(string[] args)
{
var randomNumbers = new Dictionary<int, int>();
foreach (var s in Enumerable.Range(1, 500))
{
var rand = Rand5();
if (!randomNumbers.ContainsKey(rand))
randomNumbers.Add(rand, 1);
else
randomNumbers[rand] += 1;
}
randomNumbers
.ToList()
.ForEach(x => Console.WriteLine("{0}: {1}", x.Key, x.Value));
Console.ReadLine();
}
static int Rand5()
{
System.Threading.Thread.Sleep(1);
return new Random().Next(1, 6);
}
If I comment out System.Threading.Thread.Sleep(1);
, I get
5: 500
But if I uncomment that line, I do get random numbers.
2: 87
4: 94
1: 116
5: 108
3: 95
Why does the line of code matter? Thanks!
As others have said, new Random()
seeds the random number generator from the current system time.
I have an article describing this in more detail, including solutions to the problem, which you may find useful. Basically you want to use the same instance of Random
multiple times - but observing that it's not thread-safe.
这篇关于为什么Random()不是随机的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!