Multiple random numbers are the same [duplicate]
The reason this happens is that every time you do a new Random
it is initialized using the clock. So in a tight loop (or many calls one after the other) you get the same value lots of times since all those random variables are initialized with the same seed.
To solve this: Create only one Random variable, preferably outside your function and use only that one instance.
Random random1 = new Random();
private void Draw()
{
int randomNumber1 = random1.Next(0, 300);
int randomNumber2 = random1.Next(0, 300);
int randomNumber3 = random1.Next(0, 300);
int randomNumber4 = random1.Next(0, 300);
System.Drawing.Graphics g = this.CreateGraphics();
Pen green = new Pen(Color.Green, 5);
g.DrawLine(green, new Point(randomNumber1, randomNumber2), new Point(randomNumber3, randomNumber4));
}
Simply use the same instance:
Random random = new Random();
int randomNumber1 = random.Next(0, 300);
int randomNumber2 = random.Next(0, 300);
//...
Random numbers in programming are not really random; they are based on some unique seed that is taken and manipulated to generate what appears to be set of random numbers. Using the same seed will result in same set of numbers.
The default constructor of the Random
class is using the number of milliseconds elapsed since the system started as the seed, so what actually happened is the same seed was used.
There is really no reason to create more than once Random
instance; the single instance will generate random set of numbers on each execution of the code.
To prove my above statement of default seed, I used reflection:
// System.Random
/// <summary>Initializes a new instance of the <see cref="T:System.Random" /> class, using a time-dependent default seed value.</summary>
public Random() : this(Environment.TickCount)
{
}
And the Environment.TickCount
:
// System.Environment
/// <summary>Gets the number of milliseconds elapsed since the system started.</summary>
/// <returns>A 32-bit signed integer containing the amount of time in milliseconds that has passed since the last time the computer was started.</returns>
/// <filterpriority>1</filterpriority>
public static extern int TickCount
{
[SecuritySafeCritical]
[MethodImpl(MethodImplOptions.InternalCall)]
get;
}