-2

Is rand.Next(randSeed.Next(1,10), randSeed2.Next(10, 20)) more random than rand.Next(1,20)?

I'm always getting the same number from the random class when i run code every 10 minutes (using a timer from the system.timers.timer class)

Carson McManus
  • 314
  • 5
  • 10
  • 3
    What are you using to seed your Random object? (rand) If you always use the same seed, and you're re-initializing the object every time 10 minutes, it'll keep giving the same random number. – Chris May 05 '14 at 23:55
  • 2
    please try searching first: there are a gazillion similar questions – Mitch Wheat May 05 '14 at 23:56
  • wow that was nearly instant. I found this: http://stackoverflow.com/questions/7251714/c-sharp-random-numbers-arent-being-random?rq=1 but i still need an answer to my question. – Carson McManus May 06 '14 at 00:00

1 Answers1

3

A seed is used to initialize a random number generator, like so:

Random rand = new Random(1234);  // 1234 is the seed.

Or to make it different each time your program is run, you can do this:

Random rand = new Random((int) DateTime.Now.Ticks);  // Use current time for seed.

or simply:

Random rand = new Random();  // If you don't specify a seed, it uses the current time by default.

Note: If you use a fixed seed number, then you will get the same sequences of output from Rand() each time after initialization.


Only after the seed initialization do you start to use the random number generator normally (such as calling Next()). In other words, seeds are not supposed to be used as parameters of Next().

If, however, you are trying to make the seed itself more 'random' by using another random number generator to produce it, then don't bother. Mathematically, this won't be any more random. You are better off using a cryptographic random number generator instead, such as RNGCryptoServiceProvider.

Note: Although cryptographic random number generators are more 'random', they are also slower.

SF Lee
  • 1,767
  • 4
  • 17
  • 32
  • Thanks, this'll solve my problem, but i would like an answer to my initial question. (Is rand.Next(randSeed.Next(1,10), randSeed2.Next(10, 20)) more random than rand.Next(1,20)?) – Carson McManus May 06 '14 at 00:29
  • @Dev, why do you ask? If you don't need cryptographic-level randomness, then there is no difference. If you do, neither are acceptably random. – Michael Petrotta May 06 '14 at 00:36
  • @Dev As I mentioned in my answer: "_Mathematically, this won't be any more random._" – SF Lee May 06 '14 at 00:58