我在谷歌上搜索 RNGCryptoServiceProvider,其中包含有关如何限制最大值和最小值之间的范围并仍然获得均匀分布的示例。在我使用模运算符之前,但有时我会得到奇怪的值(高于最大值)... 无论如何,每次调用该方法时,此代码(归功于未知)使用来自 RNGCCryptoServiceProvider 的新种子随机播种。你们有什么感想?
public static int GetRandom(int min, int max)
{
byte[] b = new byte[sizeof(int)];
new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
int i = BitConverter.ToInt32(b, 0);
Random r = new Random(i);
return r.Next(min, max);
}
最佳答案
使用加密类随机生成器作为常规随机生成器的种子是没有意义的。 (根据最薄弱环节的原则......)只需使用随机生成器的单个实例,并重用它:
private static Random rnd = new Random();
public static int GetRandom(int min, int max) {
return rnd.Next(min, max);
}
关于c# - "good"这个方法是怎么产生随机数的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16616521/