Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the C# random number generator guaranteed to be stable?

Tags:

c#

random

I am writing a program which uses a lot of random numbers to generate stuff. But I want to assure that when starting with the same seed the generated content is the same. So when I create my random number like this:

Random r = new Random(seed);
int num = r.Next(); 

How is it guaranteed that num is always the same over time (means: several releases of .NET)? Is there a standardized list in the background? Or should I use my own "random list" to be sure that this will never change?

like image 330
Gener4tor Avatar asked Oct 20 '25 15:10

Gener4tor


1 Answers

No, the result from the same seed can vary across versions of the framework, and it's in the documentation here:

The implementation of the random number generator in the Random class isn't guaranteed to remain the same across major versions of the .NET Framework. As a result, you shouldn't assume that the same seed will result in the same pseudo-random sequence in different versions of the .NET Framework.

That documentation also contains variations of this advice in other sections, e.g. in Retrieve the same sequence of random values:

The following example uses 100100 as an arbitrary seed value to instantiate the Random object, displays 20 random floating-point values, and persists the seed value. It then restores the seed value, instantiates a new random number generator, and displays the same 20 random floating-point values. Note that the example may produce different sequences of random numbers if run on different versions of the .NET Framework.

And:

However, note that Random objects in processes running under different versions of the .NET Framework may return different series of random numbers even if they're instantiated with identical seed values.

like image 109
stuartd Avatar answered Oct 23 '25 04:10

stuartd