Why isn't random () random?

Possible duplicate:
Why is the random number generator not random?

I have this test program:

static void Main(string[] args) { var randomNumbers = new Dictionary<int, int>(); foreach (var s in Enumerable.Range(1, 500)) { var rand = Rand5(); if (!randomNumbers.ContainsKey(rand)) randomNumbers.Add(rand, 1); else randomNumbers[rand] += 1; } randomNumbers .ToList() .ForEach(x => Console.WriteLine("{0}: {1}", x.Key, x.Value)); Console.ReadLine(); } static int Rand5() { System.Threading.Thread.Sleep(1); return new Random().Next(1, 6); } 



If I comment on System.Threading.Thread.Sleep(1); , I get

 5: 500 

But if I uncomment this line, I get random numbers.

 2: 87 4: 94 1: 116 5: 108 3: 95 

Why does a line of code matter? Thanks!

+7
source share
6 answers

As others have said, new Random() tracks a random number generator from the current system time.

I have an article describing this in more detail, including solutions to a problem that may be useful. Basically, you want to use the same instance of Random several times, but notice that it is not thread safe.

+10
source

The type Random seeded by default in accordance with the current system time, which has finite detail.

When calling new Random().Next(1, 6) many times in a row, it creates many Random objects with the same initial value, which gives the same result. Calling Thread.Sleep(1) "solves" this problem by simply separating the constructs further from each other in time, increasing the likelihood of different seed values.

You need to save a specific Random object from one call to the following:

 var randomNumbers = new Dictionary<int, int>(); var random = new Random(); // Re-use this, don't keep creating new ones. foreach (var s in Enumerable.Range(1, 500)) { var rand = random.Next(1, 6); // ... 
+11
source

Because it uses the clock as a seed to generate numbers, and when you randomly generate random numbers, you get the same numbers

+3
source

The random number generator is partly based on the system clock, and C # damn it too quickly ...

+2
source

If you don’t seed random, you will get the same number as Random - a pseudo-random generator

Using Thread.Sleep (1), you let the timer advance and generate a new auto-generated seed.

The way to β€œfix” is to create 1 random object and reuse it (as some others also answered) or use another random generator.

Additional information about http://msdn.microsoft.com/en-us/library/ctssatww.aspx

+1
source

Any random number generator you use is a pseudo random number. This will always have a predefined initial value and is useful for testing, but not for implementing true randomness functions.

You should use a sequence of quasi-random numbers to generate random numbers, or better yet, a Markov chain to generate the best random numbers. If you plan to use one of these random functions, you will not be close to true randomness.

0
source

All Articles