Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

c# - Random number seed targeting the same version of the .NET framework

Does every CPU return the same random sequence based on the same seed if my application targets .NET framework 3.5? I am checking if you get the same result as me. I am also hoping that everyone who I distribute my application to will get the same result. Thanks!

Random a = new Random(44448);
int i1 = a.Next(65, 90);
MessageBox.Show(i1.ToString());
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For a specific framework version your program should give the same result each time you run it, because of the fixed seed.

But it can give different results on different versions of the .NET framework.

For example, on .NET 4.0 I get 77. But putting the code into ideone (which uses Mono) gives 67.

The reason for this difference is because the precise algorithm used by Random is not part of the specification. The documentation has this information about the algorithm:

The current implementation of the Random class is based on a modified version of Donald E. Knuth's subtractive random number generator algorithm. For more information, see D. E. Knuth. "The Art of Computer Programming, volume 2: Seminumerical Algorithms". Addison-Wesley, Reading, MA, second edition, 1981.

...

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.

Emphasis mine. There are no guarantees that future implementations will use the same algorithm.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...