开发者

Random number generator always picks the same value when run inside a loop

The problem with the code is, when I try to generate a number, if the spin is equal 1 it generates values inside range (1,2,3) if if try to use the loop to sum random values inside the same range the random number gerated is always the same while in loop,

example, if I run the loop with: spind3 = 4 the values go from 4, 8, 12 spind3 = 5 the values go from 5, 10, 15

That means the first time the RandomNumber generates a value inside loop, it never change until the loop completes.

if (toggled3.Checked)
   {
    if (spind3.Value != 1)
        {           
         for (int i = 1; i <= spind3.Value; i++)
              {
               diceCalc[1] += RandomNumber(1, 4);
              }
        }
     else
     diceCalc[1] = RandomNu开发者_运维问答mber(1, 4);
     }


You are probably creating a new Random object inside RandomNumber method. The default constructor for Random uses the system time as a seed. If you create multiple Random objects in a tight loop the time probably won't have changed between each call so they will all be initialized with the same seed.

To fix your code you should only create one Random object and reuse it.


From the documentation:

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.


The problem is that you are creating random generators too close in time. The random generator constructor uses the current time to seed the generator, and when you create them too close in time they will all be seeded using the same time.

Create one random generator and use in the loop:

Random rnd = new Random();
for (int i = 1; i <= spind3.Value; i++) {
  diceCalc[1] += rnd.Next(1, 4);
}


You need to initialize your Random object, then call Next() inside your loop.

i.e.

if (toggled3.Checked)
{
  // initialize your total and the random number generator
  int diceTotal = 0;
  Random rand = new Random();

  for (int i = 0; i < spind3.Value; i++)
  {
    // add the next random number between 1 and 3
    diceTotal += rand.Next(1, 4); 
  }
}


You can use Random(seed) constructor.

Random rand = new Random(Guid.NewGuid().GetHashCode());


One trick is to manually create the seed by adding DateTime.Now.Ticks to the variable i:

Random r = new Random((int)DateTime.Now.Ticks + i);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜