Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Random.Next() always return the same number [duplicate]

Tags:

c#

random

clr

Consider this method:

private static int GenerateRandomNumber(int seed, int max)
{
   return new Random(seed).Next(max);
}

On my machine, executing this loop yields the same number through 1500 iterations:

  for (int i = 0; i < 1501; i++)
            {
                int random = GenerateRandomNumber(100000000, 999999999);
                Console.WriteLine(random.ToString());
                Console.ReadKey();
            }

I get 145156561, for every single iteration.

I don't have a pressing issue, I was just curious about this behavior because .Next(max) says "Returns a Non Negative random number less than the specified maximum. Perhaps I am not understanding something basic.

like image 809
Ta01 Avatar asked Mar 10 '11 18:03

Ta01


People also ask

What does a random object next method return?

Next() Returns a non-negative random integer.

Can random numbers repeat?

No, while nothing in computing is truly random, the algorithms that are used to create these "random" numbers are make it seem random so you will never get a repeating pattern.


3 Answers

You're always seeding a new instance with the same seed, and then grabbing the first max. By using a Seed, you're guaranteeing the same results.

If you want to have a static, random number generation that does different results, you should rework this a bit. However, since Random is not threadsafe, it requires some synchronization when used statically. Something like:

private static Random random;
private static object syncObj = new object();
private static void InitRandomNumber(int seed)
{
     random = new Random(seed);
}
private static int GenerateRandomNumber(int max)
{
     lock(syncObj)
     {
         if (random == null)
             random = new Random(); // Or exception...
         return random.Next(max);
     }
}
like image 71
Reed Copsey Avatar answered Oct 21 '22 13:10

Reed Copsey


Dilbert has encountered the same problem back in 2001:

http://dilbert.com/strips/comic/2001-10-25/

Coincidence?

I don't think so.

And random.org agrees : http://www.random.org/analysis/

like image 43
dbrin Avatar answered Oct 21 '22 12:10

dbrin


The problem is that you are creating a new Random instance with the same seed number each time. You should create a single Random instance (store it in a static if necessary) and simply call the next method on that same instance.

Random number generation is not truly random, see this Wikipedia entry for more details.

like image 6
Eric Giguere Avatar answered Oct 21 '22 13:10

Eric Giguere