Sunday, January 6, 2008

Random producing same values

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/random_producing_same_values.htm]

In programming languages, Random numbers aren't truly random, but rather appear random based on a seed value. For example, a trivial "random" number generator may just take the current milliseconds from the timestamp.

The following two snippets illustrate this. Each snippet runs through a loop to generate a list of "random" numbers. However, the first snippet produces all the same values because the Random generator is re-called in the loop each time, therefore the same seed appears to get used. This is bad. The second snippet is the way to do it - put the Random generator outside of the loop, and then re-call it each time to get the next random value.

While this example is obvious, it may be a little harder to see if a developer puts the Random() call in a method, and then calls the method within the loop. In that case, it would act like the first snippet, and always generate the same values.

 

    [TestMethod]
    public void Random_Bad()
    {
      List<int> li= new List<int>();
      for (int i = 0; i < 3; i++)
      {
        Random r = new Random();
        li.Add(r.Next(0, 1000000));
      }

      Assert.AreNotEqual(li[0], li[1]);  //Fail
      Assert.AreNotEqual(li[1], li[2]);  //Fail
    }

    [TestMethod]
    public void Random_Good()
    {
      List<int> li = new List<int>();
      Random r = new Random();
      for (int i = 0; i < 3; i++)
      {
        li.Add(r.Next(0, 1000000));
      }

      Assert.AreNotEqual(li[0], li[1]);
      Assert.AreNotEqual(li[1], li[2]);
    }

 

No comments:

Post a Comment