Why is this random number generator not random?

Possible duplicates:
Why doesn't my random number generator seem to be random in C #?
The random number generator does not work as I planned (C #)

I have this method for calculating a random value:

private double getMetrics(SourceFile sf) { Random r = new Random(); return (r.NextDouble()); } 

However, it always returns the same number, in my case 0.41500350386603

Why????

+1
source share
2 answers

new Random() uses the current time as the starting value. Thus, if you call this function several times in a very short period of time, it can return the same value. Here's an explanation from MSDN :

The initial default value is derived from the system clock and has a final resolution. As a result, various Random objects that are created in close sequence when the default constructor is called will have the same initial default values โ€‹โ€‹and, therefore, will create the same sets of random numbers. This problem can be avoided by using one random object to generate all random numbers.

+9
source

Just declare Random from your method, and every time you call the method, new numbers will be created if they are not deleted and not restored. When you re-create the numbers will again coincide with the beginning. You can make it wait a few ms before creating a random number if you want โ€œmoreโ€ unique numbers. If you need very unique numbers, GuID is better.

0
source

All Articles