如何“好"?这是生成随机数的方法吗? [英] How "good" is this method for generating random numbers?

查看:76
本文介绍了如何“好"?这是生成随机数的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Google上搜索RNGCryptoServiceProvider,并提供了有关如何限制最大和最小范围之间的示例的示例,并且仍然获得了均匀分布.在我使用模运算符之前,但有时我得到奇怪的值(高于Max)... 无论如何,每次调用该方法时,此代码(贷记到未知数)都随RNGCCryptoServiceProvider中的新种子一起随机发送.你们有什么感想?

I was searching on google for RNGCryptoServiceProvider with examples on how to limit the range between Max and Min, and still get an even distribution. Before I used modulo operator, but sometimes it I get strange values (above Max)... Anyways this code (credit to unknown) seeds Random with a new seed from RNGCCryptoServiceProvider, everytime the method is called. What do you guys think?

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);
}

推荐答案

您将要创建一次RNGCryptoServiceProvider对象,然后在每次需要新的随机数时重新使用该对象.例如,您可以将所述对象传递到您的GetRandom()方法中,或将其存储在类级别的字段中.

You'll want to create your RNGCryptoServiceProvider object once and then re-use that object every time you want a new random number. For instance, you can either pass said object into your GetRandom() method or store it in a class-level field.

RNGCryptoServiceProvider类型本身而言,它自己会产生良好的数字,因此无需创建Random对象并传递种子.这样可以使您的发行非常不错:

As far as the RNGCryptoServiceProvider type itself, it generates good numbers on its own, there's no need to create a Random object and pass in a seed. This should give you a very decent distribution:

public static int GetRandom(RNGCryptoServiceProvider rngProvider, int min, int max)
{
    byte[] b = new byte[sizeof(UInt32)];
    rngProvider.GetBytes(b);
    double d = BitConverter.ToUInt32(b, 0) / (double)UInt32.MaxValue;
    return min + (int)((max - min) * d);
}

这篇关于如何“好"?这是生成随机数的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆