开发者

Why does this Random Number Generator not random? [duplicate]

This question already has answers here: Closed 12 years ago.

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());
        }

Howev开发者_StackOverflow中文版er it returns always the same number, in my case 0.41500350386603

Why????


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:

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.


Just declare the Random out of your method and everytime you call the method, new numbers will be created unless it gets disposed and recreated. When re-created, the numbers will be alike with the start again. You can make it wait a few ms before creating the random number if you want "more" unique numbers. If you want very unique numbers, GuID is better.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜