4

Possible Duplicate:
Random number generator not working the way I had planned (C#)

I have made a simple routine which generates a random number

private int randomNumber()
{
    Random random = new Random();
    int randomNum = random.Next(0, 100);
    Response.Write(randomNum);
    return randomNum;
}

I call this at two different stages throughout my page_load in the same way:

// A/B Test
if (randomNumber() <= 50)
{
...

I'm finding though, that both numbers are always the same. Any ideas?

Community
  • 1
  • 1
Chris
  • 2,630
  • 3
  • 31
  • 58

4 Answers4

13

When you create a Random instance it's seeded with the current time. So if you create several of them at the same time they'll generate the same random number sequence. You need to create a single instance of Random and use that.

Dave Carlile
  • 7,347
  • 1
  • 20
  • 23
  • Well, either a single instance per thread, or a single instance with locking... – Jon Skeet May 24 '12 at 16:44
  • looks like the `Random` takes only the time part into consideration? I mean if a daily job runs at the same time (with different date of course), the random used in the job will still generate the same value (somehow). I'm not sure if the values are exactly same but I have a list ordered by the random values and somehow the list is always ordered in the same way. – Hopeless Jan 20 '20 at 10:06
7

new Random() is initialized with current time as a seed. If you call it fast enough, then the seed will be the same and so is the result of Next() call.

Ilia G
  • 10,043
  • 2
  • 40
  • 59
3

You could solve this by having single instance of Random in your class and reuse it for generating the random numbers

public class TestPage : Page
{
    private Random Generator {get;set;}
    public Test()
    {
        this.Generator = new Random();
    }
    private int randomNumber()
    {
        return this.Generator.Next(0, 100);
    }
}

This would create a Random class for every request. If you would like this to be in a group of users, you can wrap your generation logic in a Singleton and share the same instance across all users.

Ramesh
  • 13,043
  • 3
  • 52
  • 88
2

Random

Initializes a new instance of the Random class, using a time-dependent default seed value.

from MSDN.

The default seed value is derived from the system clock and has finite resolution. As a result, different Random objects that are created in close succession by a call to the default constructor will have identical default seed values and, therefore, will produce identical sets of random numbers. This problem can be avoided by using a single Random object to generate all random numbers. You can also work around it by modifying the seed value returned by the system clock and then explicitly providing this new seed value to the Random(Int32) constructor. For more information, see the Random(Int32) constructor.

Community
  • 1
  • 1
Neil Knight
  • 47,437
  • 25
  • 129
  • 188