2

If I am using the Random class in .Net(4.5) and I am always using the same seed to generate 1000 numbers is there a chance that on a different machine (with diff chipset / number of cores, etc) that my 1000 numbers could be different? I don't see how that could be, but was told by one of my colleagues that we need to be aware that they could be. The testing I have done seems to always be consistent. Just concerned that I could have a scenario where I could get different numbers. I could understand it being different if I was trying to parallize the generation or something.

int seed = 99;
var random = new Random(seed);

for (int i = 0; i < 1000; i++)
   random.Next();
Jonathan Nixon
  • 4,940
  • 5
  • 39
  • 53
scarpacci
  • 8,957
  • 16
  • 79
  • 144
  • 2
    You set is not random if you're using the same seed each time. If you want a static pseudo-random sequence just generate it once and hard-code it. – D Stanley Oct 24 '13 at 16:30
  • 1
    @DStanley Consider, for example, that you log the seed used to generate random numbers in a prod environment. Can you be sure to get the same sequence in a development environment when using that same seed to try to replicate a problem? – Servy Oct 24 '13 at 16:31

2 Answers2

8

Between different PCs running the same framework sounds unlikely (meaning: you can reasonably expect the same sequences) - but MS do reserve the right to change the implementation. MSDN states:

The implementation of the random number generator in the Random class is not guaranteed to remain the same across major versions of the .NET Framework. As a result, your application code should not assume that the same seed will result in the same pseudo-random sequence in different versions of the .NET Framework.

So: if you need a stronger guarantee: use your own PRNG implementation. There are plenty of such to choose from.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • +1. I'd not be surprised if one day `Rand` will behave as random per-AppDomain (similar to new option for `String.GetHashCode()` - [UseRandomizedStringHashAlgorithm](http://msdn.microsoft.com/en-us/library/jj152924.aspx)) – Alexei Levenkov Oct 24 '13 at 16:48
3

According to this link, you will get the same sequence in all cases for .Net 4.5 Not sure if that applies to different versions of .Net framework (agreeing with previous answer).

MSDN

"Providing an identical seed value to different Random objects causes each instance to produce identical sequences of random numbers."

nycdan
  • 2,819
  • 2
  • 21
  • 33