Why do I keep getting two of same random values in this code? [duplicate]
Possible Duplicate:
Why does it appear that my random number generator isn&开发者_运维知识库#39;t random in C#?
I have the following code:
int a;
int aa;
Random aRand = new Random();
Random aaRand = new Random();
a = aRand.Next(20);
aa = aaRand.Next(20);
//if (a == aa)
{
Console.WriteLine(a + " " + aa);
Console.ReadLine();
}
I'm assuming that aRand and aaRand would be two different values, but that's not the case. What am I doing wrong? I'm assuming that aRand and aaRand will not always be the same, but they keep coming out the same all the time.
Thanks
This is explicitly covered in the docs for Random():
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.
Why are you creating two different Random variables? You could use just one:
int a;
int aa;
Random aRand = new Random();
a = aRand.Next(20);
aa = aRand.Next(20);
//if (a == aa)
{
Console.WriteLine(a + " " + aa);
Console.ReadLine();
}
Edit: "The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value, while its parameterized constructor can take an Int32 value based on the number of ticks in the current time. " from http://msdn.microsoft.com/en-us/library/system.random.aspx
You only need one instance of Random()
- just call .Next()
twice.
int a;
int aa;
Random aRand = new Random();
a = aRand.Next(20);
aa = aRand.Next(20);
You should never have more than One Random variable in your entire application. Get rid of the second
Random aaRand = new Random();
It looks like the two instances are using the same seed.
the seed determines all the values that will be generated and in which order. If you create 200 instances of Random with the same seed, they'll all give you the same output.
Create a single Instance when your app starts and reuse it.
精彩评论