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

Viewed 936

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?

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

To be explicit: no, there isn't a "standardized list" - it is a PRNG, so it just does the same mathematical operations over and over and over - which does make it predictable (deterministic) from the same seed, as long as no-one changes the PRNG algorithm being used. Given that people often use Random for things like seeding test data, I think it would cause an outcry if it suddenly changed (without it being opt-in in some way, like a new constructor parameter), so I would find it unlikely to do so (and they haven't to date), but: if "unlikely" isn't good enough, you could always just implement any of a number of PRNG algorithms in your own code.

Related