Are Your Random Numbers Truly Random?

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.

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 www.karlmoore.com.

# # #

Please enable Javascript in your browser, before you post the comment! Now Javascript is disabled.