1

I noticed, when using System.Random, that if Next() is called more than one time in a millisecond, it returns the same number (if it has the same parameters). I assume the random algorithm somehow concerns the system's time, and is dependent on that.

I'd like to call Next() many times within a single millsecond - is there a way to do this, hopefully with the same Random class? If not, I'd appreciate any resources/other methods of solving this.

Wilson
  • 8,570
  • 20
  • 66
  • 101
  • 6
    Are you sure you're not doing `new Random().Next()` every time? – Oliver Charlesworth Jul 25 '13 at 16:06
  • 2
    _the random algorithm somehow concerns the system's time_ - No, it doesn't. But creating new Random instances in quick succession produces what you describe. It's not `Next()` but the default constructor. – H H Jul 25 '13 at 16:08
  • There's a lot of useful information about `Random` here: http://csharpindepth.com/Articles/Chapter12/Random.aspx – David Jul 25 '13 at 16:08
  • I agree with @OliCharlesworth, you're doing it wrong. There's no way a pseudo-random number generator used properly would have the problem you're describing. Show us some code. – Mark Ransom Jul 25 '13 at 16:09
  • Read http://msmvps.com/blogs/jon_skeet/archive/2009/11/04/revisiting-randomness.aspx – Yuriy Faktorovich Jul 25 '13 at 16:11

1 Answers1

6

This is because when you initialise a new instance of Random it uses the system clock for the seed. If you do this twice, close enough together, you'll end up using the same seed and so you'll get the same sequence of random numbers from the two instances.

The solution as alluded to in comments already, is to instantiate one Random object and then repeatedly call Next() on it, you'll get a new random number every time.

var val1 = new Random().Next();
var val2 = new Random().Next(); // quite likely val1 and val2 will be the same

var rnd = new Random();
var val3 = rnd.Next();
var val4 = rnd.Next(); // very unlikely val3 and val4 will be the same
Jon G
  • 4,083
  • 22
  • 27
  • 1
    Even if you don't do it fast enough to get the same values back, you'll destroy the randomness of the generator since the seeds are definitely non-random. – Mark Ransom Jul 25 '13 at 16:21