Forum C# Random generator acting weird

Random generator acting weird

Postby GBurg » June 6th, 2011, 9:10 pm

Hi all,

I have a weird problem. I have the following code:

void test() {
Random r = new Random();
Console.WriteLine(r.NextDouble());
Console.WriteLine(r.NextDouble());
}

test();
test();
test();
test();
test();

Each time test is called, 2 random numbers are generated. The first number is very small < 0.02, while the other is just between 0 and 1 .

What do I miss, and how to make the first number normal (between 0 and 1, not between 0 and 0.02)?
GBurg
Paid Member
 
Posts: 78
Joined: February 9th, 2011, 10:27 am

Re: Random generator acting weird

Postby Henrik » June 6th, 2011, 10:13 pm

When you create a new Random instance, it will have a seed, and if you have two instances with the same seed, they will produce the exact same sequence of random numbers.

If you instantiate a Random without any parameters, the seed defaults to the system time, and if you make five calls right after the other, some of those will have the same seed since the calls will come in faster than the system time changes.

The solution is of course to not create new instances of Random all the time. Make one and keep it for a while.
Henrik
.IO
 
Posts: 1880
Joined: January 4th, 2010, 1:53 pm

Re: Random generator acting weird

Postby Henrik » June 6th, 2011, 10:16 pm

Code: Select all
public Random r = new Random();

public void Test() {
   Console.WriteLine(r.NextDouble());
   Console.WriteLine(r.NextDouble());
}
Henrik
.IO
 
Posts: 1880
Joined: January 4th, 2010, 1:53 pm

Re: Random generator acting weird

Postby GBurg » June 20th, 2011, 2:05 pm

Using only one random instance indeed solved my problem. thanks!
GBurg
Paid Member
 
Posts: 78
Joined: February 9th, 2011, 10:27 am


Return to C#