1

whenever I have two random numbers being generated like so :

 Random rand1 = new Random();
 Random rand2 = new Random(23);

the second random number's value never changes

while rand1 varies on each load, rand2 always presents the value 396. Am I declaring the seed wrongly?

Dlorwisdom
  • 119
  • 1
  • 2
  • 12
  • 1
    Same seed, same sequence of "random" numbers. That's why you should use something highly unpredictable for the seed value (which it does by default) – Mike Christensen Oct 24 '14 at 02:44
  • possible duplicate of [Random number generator only generating one random number](http://stackoverflow.com/questions/767999/random-number-generator-only-generating-one-random-number) – jpw Oct 24 '14 at 02:45
  • Random() is seeded by time. [Random](http://referencesource.microsoft.com/#mscorlib/system/random.cs) – RadioSpace Oct 24 '14 at 02:53
  • Random class is anyway a pseudo random number generator, so in reality you will never achieve true randomness using the Random class, with or without seed, it surely will repeat after some time, check this extract from Jon Skeet's book C# in Depth: http://csharpindepth.com/Articles/Chapter12/Random.aspx – Mrinal Kamboj Oct 24 '14 at 03:49
  • SO I really thank you all for the comments and answers, but I realized that I was too quick to ask this question immediately after posting it and I cant delete things yet. The random number doesn't stay the same, it only produces the same first number on initial load. I was loading it up and saw the same number each time and then quit the program. Had I continued forward in my program the number would have changed. Basically: Im an idiot :/ – Dlorwisdom Oct 24 '14 at 17:32

1 Answers1

2

The second random value never change entirely by design. Moreover, if you store the first 100 or 1000 random numbers after seeding your generator to a fixed number, you would get the same sequence every time you run the program.

Seeding a pseudorandom number generator is designed specifically to let you produce a repeatable sequence of random numbers. This is very useful for testing your code that needs to use random numbers, but you want repeatable behavior for testing purposes.

In situations when you do not need to produce the same pseudorandom sequence again and again, you seed your random number generator to some changing number, for example, the current system time.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523