天天看點

【原創】開源Math.NET基礎數學類庫使用(12)C#随機數擴充方法

【原創】開源Math.NET基礎數學類庫使用(12)C#随機數擴充方法

真正意義上的随機數(或者随機事件)在某次産生過程中是按照實驗過程中表現的分布機率随機産生的,其結果是不可預測的,是不可見的。而計算機中的随機函數是按照一定算法模拟産生的,其結果是确定的,是可見的。我們可以這樣認為這個可預見的結果其出現的機率是100%。是以用計算機随機函數所産生的“随機數”并不随機,是僞随機數。僞随機數的作用在開發中的使用非常常見,是以.NET在System命名空間,提供了一個簡單的Random随機數生成類型。但這個類型并不能滿足所有的需求,本節開始就将陸續介紹Math.NET中有關随機數的擴充以及其他僞随機生成算法編寫的随機數生成器。

               本部落格所有文章分類的總目錄:【總目錄】本部落格博文總目錄-實時更新 

開源Math.NET基礎數學類庫使用總目錄:【目錄】開源Math.NET基礎數學類庫使用總目錄

前言

  真正意義上的随機數(或者随機事件)在某次産生過程中是按照實驗過程中表現的分布機率随機産生的,其結果是不可預測的,是不可見的。而計算機中的随機函數是按照一定算法模拟産生的,其結果是确定的,是可見的。我們可以這樣認為這個可預見的結果其出現的機率是100%。是以用計算機随機函數所産生的“随機數”并不随機,是僞随機數。僞随機數的作用在開發中的使用非常常見,是以.NET在System命名空間,提供了一個簡單的Random随機數生成類型。但這個類型并不能滿足所有的需求,本節開始就将陸續介紹Math.NET中有關随機數的擴充以及其他僞随機生成算法編寫的随機數生成器。

  今天要介紹的是基于System.Random的擴充方法。

  如果本文顯示有問題,請參考:http://www.cnblogs.com/asxinyu/p/4301544.html

1.Random的擴充方法類

  Rondom擴充及随機數相關的類都在Math.NET的MathNet.Numerics.Random命名空間,今天要介紹的 RandomExtensions 類是 擴充Random的靜态方法類,可以直接在System.Random的對象上使用,相關功能介紹:

1.可以直接傳回填充0-1随機資料的數組,如NextDoubles方法;

2.可以傳回一個無限長度的IEnumerable接口對象,一直疊代傳回double類型的随機數,是NextDoubleSequence方法;

3.類似的還可以傳回其他類型的随機資料數組,如NextBytes,NextInt32s等;

4.還可以單獨傳回Int32類型和Int64類型的随機數,其範圍在該類型的所有值域上,如NextFullRangeInt32,NextFullRangeInt64;

5.還可以單獨傳回Int32類型和Int64類型的随機數,其範圍是該類型所有值域上的非負數,如NextInt64;

2.RandomExtensions類的實作

  作為靜态類,使用非常簡單,為了友善了解,我将注釋進行了部分翻譯,貼出該類的所有源碼,大家可以參考參考: 

1 /// <summary>這個類是對System.Random類的擴充,擴充方法可以生成更多類型的僞随機數,而不是僅僅是double和Int32類型</summary>
  2 /// <remarks>這個擴充是線程安全的,并且隻有在Math.NET提供的随機數發生器或者RandomSource的繼承類中被調用</remarks>
  3 public static class RandomExtensions
  4 {
  5     /// <summary>使用(0-1)範圍内的均勻随機數填充1個數組</summary>
  6     /// <param name="rnd">Random類型的随機數生成器</param>
  7     /// <param name="values">要填充随機數的數組</param>
  8     /// <remarks>這個擴充是線程安全的,并且隻有在Math.NET提供的随機數發生器或者RandomSource的繼承類中被調用</remarks>
  9     public static void NextDoubles(this System.Random rnd, double[] values)
 10     {
 11         var rs = rnd as RandomSource;
 12         if (rs != null)
 13         {
 14             rs.NextDoubles(values);
 15             return;
 16         }
 17 
 18         for (var i = 0; i < values.Length; i++)
 19         {
 20             values[i] = rnd.NextDouble();
 21         }
 22     }
 23 
 24     /// <summary>傳回一個(0-1)範圍内的均勻随機數填充1個數組</summary>
 25     /// <param name="rnd">Random類型的随機數生成器</param>
 26     /// <param name="count">要傳回的數組的長度</param>
 27    
 28     public static double[] NextDoubles(this System.Random rnd, int count)
 29     {
 30         var values = new double[count];
 31         NextDoubles(rnd, values);
 32         return values;
 33     }
 34 
 35     /// <summary>傳回1個無限的0-1均勻分布随機數序列</summary>
 36     public static IEnumerable<double> NextDoubleSequence(this System.Random rnd)
 37     {
 38         var rs = rnd as RandomSource;
 39         if (rs != null) return rs.NextDoubleSequence();
 40         return NextDoubleSequenceEnumerable(rnd);
 41     }
 42 
 43     static IEnumerable<double> NextDoubleSequenceEnumerable(System.Random rnd)
 44     {
 45         while (true)
 46         {
 47             yield return rnd.NextDouble();
 48         }
 49     }
 50 
 51     /// <summary>傳回1個均勻分布的byte數組</summary>
 52     /// <param name="rnd">Random類型的随機數生成器</param>
 53     /// <param name="count">要傳回的數組的長度</param>
 54     public static byte[] NextBytes(this System.Random rnd, int count)
 55     {
 56         var values = new byte[count];
 57         rnd.NextBytes(values);
 58         return values;
 59     }
 60 
 61     /// <summary>
 62     /// Fills an array with uniform random numbers greater than or equal to 0.0 and less than 1.0.
 63     /// </summary>
 64     /// <param name="rnd">The random number generator.</param>
 65     /// <param name="values">The array to fill with random values.</param>
 66     /// <param name="minInclusive">Lower bound, inclusive.</param>
 67     /// <param name="maxExclusive">Upper bound, exclusive.</param>
 68     public static void NextInt32s(this System.Random rnd, int[] values, int minInclusive, int maxExclusive)
 69     {
 70         var rs = rnd as RandomSource;
 71         if (rs != null)
 72         {
 73             rs.NextInt32s(values, minInclusive, maxExclusive);
 74             return;
 75         }
 76         for (var i = 0; i < values.Length; i++)
 77         {
 78             values[i] = rnd.Next(minInclusive, maxExclusive);
 79         }
 80     }
 81 
 82     /// <summary>
 83     /// Returns an infinite sequence of uniform random numbers greater than or equal to 0.0 and less than 1.0.
 84     /// </summary>
 85     public static IEnumerable<int> NextInt32Sequence(this System.Random rnd, int minInclusive, int maxExclusive)
 86     {
 87         var rs = rnd as RandomSource;
 88         if (rs != null)
 89         {
 90             return rs.NextInt32Sequence(minInclusive, maxExclusive);
 91         }
 92         return NextInt32SequenceEnumerable(rnd, minInclusive, maxExclusive);
 93     }
 94 
 95     static IEnumerable<int> NextInt32SequenceEnumerable(System.Random rnd, int minInclusive, int maxExclusive)
 96     {
 97         while (true)
 98         {
 99             yield return rnd.Next(minInclusive, maxExclusive);
100         }
101     }
102 
103     /// <summary>傳回Int64類型的非負随機數</summary>
104     /// <param name="rnd">Random類型的随機數生成器</param>
105     /// <returns>
106     /// A 64-bit signed integer greater than or equal to 0, and less than <see cref="Int64.MaxValue"/>; that is, 
107     /// the range of return values includes 0 but not <see cref="Int64.MaxValue"/>.
108     /// </returns>
109     /// <seealso cref="NextFullRangeInt64"/>
110     public static long NextInt64(this System.Random rnd)
111     {
112         var buffer = new byte[sizeof (long)];
113 
114         rnd.NextBytes(buffer);
115         var candidate = BitConverter.ToInt64(buffer, 0);
116 
117         candidate &= long.MaxValue;
118         return (candidate == long.MaxValue) ? rnd.NextInt64() : candidate;
119     }
120 
121     /// <summary>
122     /// Returns a random number of the full Int32 range.
123     /// </summary>
124     /// <param name="rnd">The random number generator.</param>
125     /// <returns>
126     /// A 32-bit signed integer of the full range, including 0, negative numbers,
127     /// <see cref="Int32.MaxValue"/> and <see cref="Int32.MinValue"/>.
128     /// </returns>
129     /// <seealso cref="System.Random.Next()"/>
130     public static int NextFullRangeInt32(this System.Random rnd)
131     {
132         var buffer = new byte[sizeof (int)];
133         rnd.NextBytes(buffer);
134         return BitConverter.ToInt32(buffer, 0);
135     }
136 
137     /// <summary>
138     /// Returns a random number of the full Int64 range.
139     /// </summary>
140     /// <param name="rnd">The random number generator.</param>
141     /// <returns>
142     /// A 64-bit signed integer of the full range, including 0, negative numbers,
143     /// <see cref="Int64.MaxValue"/> and <see cref="Int64.MinValue"/>.
144     /// </returns>
145     /// <seealso cref="NextInt64"/>
146     public static long NextFullRangeInt64(this System.Random rnd)
147     {
148         var buffer = new byte[sizeof (long)];
149         rnd.NextBytes(buffer);
150         return BitConverter.ToInt64(buffer, 0);
151     }
152 
153     /// <summary>
154     /// Returns a nonnegative decimal floating point random number less than 1.0.
155     /// </summary>
156     /// <param name="rnd">The random number generator.</param>
157     /// <returns>
158     /// A decimal floating point number greater than or equal to 0.0, and less than 1.0; that is, 
159     /// the range of return values includes 0.0 but not 1.0.
160     /// </returns>
161     public static decimal NextDecimal(this System.Random rnd)
162     {
163         decimal candidate;
164 
165         // 50.049 % chance that the number is below 1.0. Try until we have one.
166         // Guarantees that any decimal in the interval can
167         // indeed be reached, with uniform probability.
168         do
169         {
170             candidate = new decimal(
171                 rnd.NextFullRangeInt32(),
172                 rnd.NextFullRangeInt32(),
173                 rnd.NextFullRangeInt32(),
174                 false,
175                 28);
176         }
177         while (candidate >= 1.0m);
178 
179         return candidate;
180     }
181 }      

  其使用非常簡單,這裡就不再舉例子。這種擴充大家也應該寫過,後面幾篇文章将介紹Math.NET中實作的其他算法的随機數發生器。請關注

3.資源

  源碼下載下傳:http://www.cnblogs.com/asxinyu/p/4264638.html

  如果本文顯示有問題,請參考本文原文:http://www.cnblogs.com/asxinyu/p/4301544.html

.NET資料挖掘與機器學習,作者部落格:

http://www.cnblogs.com/asxinyu

E-mail:[email protected]

繼續閱讀