为什么这个随机数发生器不是随机的? [英] Why does this Random Number Generator not random?
问题描述
可能显示的文件:
<一href="http://stackoverflow.com/questions/932520/why-does-it-appear-that-my-random-number-generator-isnt-random-in-c">Why它似乎我的随机数生成器是不是随机在C#?
<一href="http://stackoverflow.com/questions/767999/random-number-generator-not-working-the-way-i-had-planned-c">Random数生成器不工作我已经计划的方式(C#)
Possible Duplicates:
Why does it appear that my random number generator isn't random in C#?
Random number generator not working the way I had planned (C#)
我有这样的方法来计算一个随机值:
I have this method to calculate a random value:
private double getMetrics(SourceFile sf)
{
Random r = new Random();
return (r.NextDouble());
}
然而,它总是返回相同的号码,在我的情况0.41500350386603
However it returns always the same number, in my case 0.41500350386603
为什么????
推荐答案
新的随机()
使用当前时间作为种子值。因此,如果要调用该函数多次在一个很短的时间跨度,它可能返回相同的值。下面是从 MSDN 的解释:
new Random()
uses the current time as the seed value. Thus, if you are calling this function multiple times in a very short time span, it might return the same value. Here's the explanation from MSDN:
默认种子值是从系统时钟产生,并具有有限的分辨率。其结果,是由调用默认构造在靠近连续创建不同的随机的对象将具有相同的默认种子值,因此,将产生相同的套的随机数。可避免使用单一Random对象产生所有的随机数这一问题。
The default seed value is derived from the system clock and has finite resolution. As a result, different Random objects that are created in close succession by a call to the default constructor will have identical default seed values and, therefore, will produce identical sets of random numbers. This problem can be avoided by using a single Random object to generate all random numbers.
这篇关于为什么这个随机数发生器不是随机的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!