1

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

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

Why????

Community
  • 1
  • 1
  • 2
    Thats because you are re-initializing it every time. Move the declaration & instantiation code to some other place. – shahkalpesh Dec 07 '10 at 12:13
  • Yes but e.g. if i do that in Java nevertheless, random numbers are generated –  Dec 07 '10 at 12:14
  • 1
    Then the Java random class must have a different specification. – Rup Dec 07 '10 at 12:15
  • @shakalpesh: No, `new Random()` initializes it with `Environment.TickCount` as seed, so it should never display the same value (except maybe in a **very** tight loop). – Bobby Dec 07 '10 at 12:16
  • possible duplicate http://stackoverflow.com/questions/932520/why-does-it-appear-that-my-random-number-generator-isnt-random-in-c – nan Dec 07 '10 at 12:17
  • 3
    How many times must this question still be asked? Can't we just start shooting people already for asking the same questions all the time without searching? – leppie Dec 07 '10 at 12:19
  • @shakalpesh: On second thought, he most likely used that tight loop, so I'll shut up, sorry... – Bobby Dec 07 '10 at 12:21

2 Answers2

9

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.

Heinzi
  • 167,459
  • 57
  • 363
  • 519
0

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.

Pabuc
  • 5,528
  • 7
  • 37
  • 52