1

Possible Duplicates:
Why does it appear that my random number generator isn't random in C#?
Random number generator not working the way I had planned (C#)

Hello,
I use this function (in class) to randomize numbers:

private int RandomNumber(int min, int max)
{
    Random random = new Random();
    return random.Next(min, max);
}

public void Init()
{
    x = RandomNumber(0,500);
}

However if I later call multiple object to do it:

Obj[] obj = new Obj[64];
for( int i = 0 ; i < 64 ; i++ )
{
    obj[i] = new Obj();
}
...
for( int i = 0 ; i < 64 ; i++ )
{
    obj[i].Init();
}

then each object has exactly same 'x' value.

What is wrong here?

Community
  • 1
  • 1
Neomex
  • 1,650
  • 6
  • 24
  • 38
  • And here is a better duplicate with a thread-safe answer: http://stackoverflow.com/questions/767999/random-number-generator-not-working-the-way-i-had-planned-c – H H Apr 03 '11 at 19:45

2 Answers2

5

Random should only be created once and Next called on the single instance.

This is because by default Random is seeded by the current time - if called in a tight loop (like you do), the seed will be the same and the result of the pseudo-random algorithm will mostly be identical.

If you change your code to something like this, you will get better results:

private static Random random = new Random();
private int RandomNumber(int min, int max)
{
    return random.Next(min, max);
}

However, this is not thread safe. If you try to use this in a multi threaded application, expect problems. For a thread safe version, I suggest reading and following this article by Jon Skeet.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • 1
    It's not a good idea to use a plain static variable to store a reference to an instance of `Random`, as it's not thread-safe. See http://csharpindepth.com/Articles/Chapter12/Random.aspx for more details. – Jon Skeet Apr 03 '11 at 18:56
  • No problem. It's a really nasty "gotcha" in .NET, unfortunately :( – Jon Skeet Apr 03 '11 at 19:00
2

The Random class is a pseudo-random number generator. It needs a unique seed value to produce unique numbers.

The default seed value is based on the current time, which will be the same because all your objects are created in a split-second.

Make the Random instance static or find a unique seed value for every instantiation to fix the problem.

Morten Mertner
  • 9,414
  • 4
  • 39
  • 56