Correctly Using Random Number Generators
Today I read another guy’s blog post that reminded me of my own "Aha!" moment I had a while back with Random Number Generators. It’s something I will never forget about Random Number Generators but taken for granted, realizing that it might not be obvious to everyone how these objects are intended to be used. Here is the blog entry that I read about creating and seeding a Random Number Generator once:
However, I must admit that I think Mike Snow should have titled his post something similar to the title of my post. And I will tell you why…
In the MSDN documentation that Mike quotes, there is a key sentence everyone needs to take note of, as you can ignorantly introduce bugs into your code:
"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."
I have actually build a piece of code where this has happened. I wrote a for loop that iterated quickly enough that the construction of the Random objects resulted in identical random number seeds. The result was that I asked for several random numbers in quick succession and got the same exact "random" number across all my requests each time I ran the code. So not only did I get "identical sets of random numbers," but I got identical random numbers.
As Mike Snow and the MSDN documentation states (and from my own experience), Random Number Generators are designed to be constructed once and intended to live long and prosper within your application. It can serve all of the random number needs within your application (i.e., you don’t need a different Random Number Generator for different use cases or different object types). All you need is a one-time created random number seed and then you can forever generate random numbers of any type and within any range of numbers. I can’t currently think of a situation when you may need to reseed your Random Number Generator. Let me know if you think of one.