System.Random rnd = new System.Random(); 有多随机 [英] How random is System.Random rnd = new System.Random();
问题描述
我有一些可以运行的代码.在我执行的循环内:
I have some code that runs. Inside of a loop I execute:
System.Random rnd = new System.Random();
如果在运行呼叫之间几乎没有时间延迟,我可以期望号码是随机的吗?
Can I expect the number to be random if there is almost no time delay between running the call?
推荐答案
来自 文档:
选择伪随机数来自有限集合的等概率数字.选择的数字不是完全随机,因为一个确定的数学算法用于选择它们,但它们足够了出于实际目的随机.这Random 的当前实现类基于修改版本Donald E. Knuth 的减法随机数生成算法.为了更多信息,请参见 D. E. Knuth.计算机编程的艺术,第 2 卷:半数值算法".Addison-Wesley,雷丁,马萨诸塞州,第二1981 年版.
Pseudo-random numbers are chosen with equal probability from a finite set of numbers. The chosen numbers are not completely random because a definite mathematical algorithm is used to select them, but they are sufficiently random for practical purposes. 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.
不考虑生成两个随机数之间的延迟.当然,这是指在同一个实例上调用 Random.Next
而不是像在您的代码中那样每次都创建一个新的 Random
实例(这是错误的):
The delay between generating two random numbers does not come into account. Of course this refers to calling Random.Next
on the same instance instead of creating a new Random
instance each time as in your code (which is wrong):
这个问题可以通过以下方式避免而是创建一个 Random 对象比多个.
This problem can be avoided by creating a single Random object rather than multiple ones.
为了提高性能,创建一个随机对象生成许多随机随着时间的推移数字,而不是反复创建一个新的随机对象生成一个随机数.
To improve performance, create one Random object to generate many random numbers over time, instead of repeatedly creating a new Random objects to generate one random number.
如果您需要生成加密强度随机性:
If you need to generate cryptographic-strength randomness:
生成一个加密安全的适合创建一个随机数随机密码,例如,使用派生自的类System.Security.Cryptography.RandomNumberGenerator如System.Security.Cryptography.RNGCryptoServiceProvider.
To generate a cryptographically secure random number suitable for creating a random password, for example, use a class derived from System.Security.Cryptography.RandomNumberGenerator such as System.Security.Cryptography.RNGCryptoServiceProvider.
这篇关于System.Random rnd = new System.Random(); 有多随机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!