Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the quality of Random class implementation in .NET?

Tags:

c#

.net

random

I have two questions regarding implementation of Random class in .NET Framework 4.6 (code available here):

  1. 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#.

  2. 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.

like image 301
houen Avatar asked Aug 10 '15 09:08

houen


People also ask

How Random class works in C#?

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.

How do you pick a random number in C#?

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);

How do I suppress ca5394?

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.


1 Answers

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.

like image 88
DGibbs Avatar answered Sep 22 '22 14:09

DGibbs