0

I would like to get random values using Random class the same each time application runs and only different when I change seed value or initialize random class.

I declare Random random = new Random(); as a global parameter.

Then I print 3 random doubles:

for (int i = 0; i < 3; i++) 
 Console.WriteLine(random.NextDouble())

Each time application runs I get different values

For instance first time I run application I get values 0.454, 0.256, 0.100

Second time 0.578, 0.123, 0.001

But what I would to have is that each time application runs I would get the same numbers

For example first time I run app I get 0.454, 0.256, 0.100 Second time 0.454, 0.256, 0.100

Petras
  • 163
  • 1
  • 1
  • 12
  • Maybe your implementation uses a random seed itself internally when you don't specify one (ex: using the current timestamp). Provide your own seed yourself if you want to make sure to get the same results every time – KABoissonneault May 25 '17 at 15:04
  • 1
    https://msdn.microsoft.com/en-us/library/ctssatww(v=vs.110).aspx "Providing an identical seed value to different Random objects causes each instance to produce **identical sequences of random numbers**. This is often done when testing apps that rely on random number generators." – Dmitry Bychenko May 25 '17 at 15:12
  • Um just what do you mean by 'global parameter'??? a class level variable, perhaps? – TaW May 25 '17 at 15:15

3 Answers3

7

Provide the random constructor with a seed such as 1, although it could be any number:

Random random = new Random(1);

Now each time you'll get the same number so it won't be random. If you don't provide it will by default take the current time stamp as the seed, so you can control the values by controlling the seed.

Here's a complete solution:

static void Main(string[] args)
        {
            Random random = new Random(1);


            for (int i = 0; i < 3; i++)
                Console.WriteLine(random.NextDouble());

            Console.Read();
        }

OUTPUT:

0.248668584157093
0.110743977181029
0.467010679872246
chris-crush-code
  • 1,114
  • 2
  • 8
  • 17
3

You could pick a hardcoded seed in your Random constructor.

When you initialize the Random class, do something like

var random = new Random(0);

The seed is the initial state of Random. By default, it depends on the system clock, so every time you initialize it in application runs, it gets a new seed and has different behavior. By picking a static seed, it will behave the same.

vcsjones
  • 138,677
  • 31
  • 291
  • 286
2

When you initialize the Random class. Provide the constructor with the same seed.

Example:

Random random = new Random(0);

This will give you the same values every time you run the program.

This is because the default constructor provides a seed value that is derived from the system clock and has finite resolution.

Brady Jessup
  • 174
  • 8