When using a Random Number Generator, which is the better way to use it for greater randomness of the new value:
Have a method that instantiates a new instance of the RNG each time and then returns a value?
Have an instance of the RNG at the class level, which is instantiated once in the Constructor, and all subsequent calls for a new random value using the existing instance?
The issue is that there may be many calls for a random number, often in different scopes not connected with each other.
This is not a performance issue, so the fact that each call might instantiate a new instance makes no difference. This is all about the randomness of the returned value.
Option 1 does not work, actually.
Option 2 is the only choice. RNG's absolutely require that you generate the values in sequence from a single seed.
Your "create a new generator with a new seed" breaks the mathematical foundation. What you get then totally depends on your seeds, which -- sadly -- won't be very random.
I suggest option 3: have a single RNG used throughout the program. It requires locking or a thread-local if the RNG isn't thread-safe (e.g. in .NET), but it makes life a lot simpler and you don't need to worry about repetition.
See the relevant MiscUtil page for details of the .NET StaticRandom class I wrote for this very purpose. (It's incredibly simple - nothing clever at all.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With