How “good” is this method for generating random numbers?

后端 未结 3 2194
别那么骄傲
别那么骄傲 2021-02-11 08:39

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 oper

3条回答
  •  情歌与酒
    2021-02-11 09:22

    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.

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

提交回复
热议问题