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

后端 未结 3 2189
别那么骄傲
别那么骄傲 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:26

    It's a better practice to seed your random number generator just one time in your application. I suggest you create a static class for random number generation. The random generation object can yield even distribution just by normal usage. I don't know whats the benefit of seeding the generator with RNGCryptoServiceProvider. I prefer using the time as seeding method as usual. Therefore the following code is my suggestion:

    int randomNumber=Rand.get(min,max);
    
    public static class Rand
    {
        private static Random rnd;
        static rand()
        {
            rand=new Random(DateTime.Now.Ticks);
        }
        public static int get(int min,int max)
        {
            return rnd.Next(min,max);
        }
    }
    

提交回复
热议问题