I have two questions regarding implementation of Random
class in .NET Framework 4.6 (code available here):
What is the rationale for setting Seed
argument to 1
at the end of the constructor? It seems to be copy-pasted from Numerical Recipes in C (2nd Ed.) where it made some sense, but it doesn't have any in C#.
It is directly stated in the book (Numerical Recipes in C (2nd Ed.)) that inextp
field is set to value 31
because:
The constant 31 is special; see Knuth.
However, in the .NET implementation this field is set to value 21
. Why? The rest of a code seems to closely follow the code from book except for this detail.
The current implementation of the Random class is based on a modified version of Donald E. Knuth's subtractive random number generator algorithm. Every time you do new Random() it is initialized using the clock. This means that in a tight loop you get the same value lots of times.
To generate random numbers in C#, use the Next(minValue, MaxValue) method. The parameters are used to set the minimum and maximum values. Next(100,200);
If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule. To disable the rule for a file, folder, or project, set its severity to none in the configuration file.
Regarding the intexp
issue, this is a bug, one which Microsoft has acknowledged and refused to fix due to backwards compatibility concerns.
Indeed, you have discovered a genuine problem with the Random implementation. We have discussed it within the team and with some of our partners and concluded that we unfortunately cannot fix the problem right now. The reason is that some applications rely on the fact that when initialised with the same seed, the generator produces the same pseudo random sequence. Even if the change is for the better, it will break the applications that made this assumption once they have migrated to the “fixed” version.
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