[C#]產生亂數,使用RNGCryptoServiceProvider

  • 1725
  • 0

經常需要使用到亂數,但是又怕Random不夠亂,所以改用RNGCryptoServiceProvider

參考Will保哥的「亂數產生器:Random 與 RNGCryptoServiceProvider
以及StackOverflow的文章,修改成給自己的亂數類別,如下:

public static class RandomValue
{
   private static RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

   /// <summary>
   /// 產生一個大於等於零且小於等於max的整數亂數
   /// </summary>
   /// <param name="max">最大值</param>
   public static int Next(int max)
   {
      var bytes = new byte[4];
      rng.GetBytes(bytes);
      int value = BitConverter.ToInt32(bytes, 0);
      value = value % (max + 1);
      if (value < 0) value = -value;
      return value;
   }

   /// <summary>
   /// 產生一個大於等於min且小於等於max的整數亂數
   /// </summary>
   /// <param name="min">最小值</param>
   /// <param name="max">最大值</param>
   public static int Next(int min, int max)
   {
      int value = Next(max - min) + min;
      return value;
   }

   /// <summary>
   /// 產生一個大於0且小於1的Double亂數
   /// </summary>
   /// <returns></returns>
   public static double NextDouble()
   {
      var bytes = new byte[8];
      rng.GetBytes(bytes);
      var ul = BitConverter.ToUInt64(bytes, 0) / (1 << 11);
      double d = ul / (double)(1UL << 53);
      return d;
   }

   /// <summary>
   /// 產生一個大於0且小於 max 的 Double 亂數
   /// </summary>
   /// <param name="max">最大值</param>
   public static double NextDouble(int max)
   {
      return NextDouble() * max;
   }

   /// <summary>
   /// 產生一個大於 min 且小於 max 的 Double 亂數
   /// </summary>
   /// <param name="min">最小值</param>
   /// <param name="max">最大值</param>
   public static double NextDouble(int min, int max)
   { 
      return NextDouble(max - min) + min;
   }

}