Microsoft & .NET.NETAre Your Random Numbers Truly Random?

Are Your Random Numbers Truly Random? content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

After reading at least a dozen articles on how to generate random numbers, I’m sorry to say that technical writers are still getting it wrong.

Don’t misunderstand me: Generating random numbers is actually very easy. You simply create a new instance of the System.Random class, passing in a “seed” value. Then, you use the object .Next method to return a fresh value. The problem is that most developers place the new instance of the Random class inside the function that generates the number itself.

This means that, if the function is run a number of times at speed, the “seed” (typically a value based on the number of “ticks” for the current date and time) given to the Random class may be the same each time. Now, the Random class is never truly random and simply runs a formula to “randomize” the next number. Because most developers are declaring a new instance of the class inside the function, it gets created afresh with every single call, follows its same formula with the same seed to generate a random number—and creates one exactly the same as the last! (Until, at least, the tick “seed” value alters).

The trick is to declare the new Random class outside of the function that retrieves the next random number. This way, you generate the seed only once and are getting the “randomizer” formula to cycle through its formula and ensure the next chosen number is truly random.

Here’s my code. Note that you no longer have to declare new objects (such as objRandom, here) at the top of your class or module; you can do it just above the function, to aid clarity of code:

Dim objRandom As New System.Random( _
 CType(System.DateTime.Now.Ticks Mod System.Int32.MaxValue, _

  Public Function GetRandomNumber( _
     Optional ByVal Low As Integer = 1, _
     Optional ByVal High As Integer = 100) As Integer
      ' Returns a random number,
      ' between the optional Low and High parameters
      Return objRandom.Next(Low, High + 1)
  End Function

And here’s how you may use this function in code:

Dim intDiceRoll As Integer
intDiceRoll = GetRandomNumber(1, 6)
MessageBox.Show("You rolled a " & intDiceRoll.ToString)

About the Author

Karl Moore (MCSD, MVP) is an experience author living in Yorkshire, England. He is the author of numerous technology books, including the new Ultimate VB .NET and ASP.NET Code Book (ISBN 1-59059-106-2, $49.99), plus regularly features at industry conferences and on BBC radio. Moore also runs his own creative consultancy, White Cliff Computing Ltd. Visit his official Web site at

# # #

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories