zoukankan      html  css  js  c++  java
  • 【原创】开源Math.NET基础数学类库使用(13)C#实现其他随机数生成器

                   本博客所有文章分类的总目录:【总目录】本博客博文总目录-实时更新 

    开源Math.NET基础数学类库使用总目录:【目录】开源Math.NET基础数学类库使用总目录

    前言

      真正意义上的随机数(或者随机事件)在某次产生过程中是按照实验过程中表现的分布概率随机产生的,其结果是不可预测的,是不可见的。而计算机中的随机函数是按照一定算法模拟产生的,其结果是确定的,是可见的。我们可以这样认为这个可预见的结果其出现的概率是100%。所以用计算机随机函数所产生的“随机数”并不随机,是伪随机数。伪随机数的作用在开发中的使用非常常见,因此.NET在System命名空间,提供了一个简单的Random随机数生成类型。但这个类型并不能满足所有的需求,本节开始就将陆续介绍Math.NET中有关随机数的扩展以及其他伪随机生成算法编写的随机数生成器。

      今天要介绍的是Math.NET中扩展的其他随机数生成算法。

      如果本文资源或者显示有问题,请参考 本文原文地址http://www.cnblogs.com/asxinyu/p/4301555.html

    http://zh.wikipedia.org/wiki/随机数

      随机数是专门的随机试验的结果。
      在统计学的不同技术中需要使用随机数,比如在从统计总体中抽取有代表性的样本的时候,或者在将实验动物分配到不同的试验组的过程中,或者在进行蒙特卡罗模拟法计算的时候等等。产生随机数有多种不同的方法。这些方法被称为随机数生成器。随机数最重要的特性是它在产生时后面的那个数与前面的那个数毫无关系。
    真正的随机数是使用物理现象产生的:比如掷钱币、骰子、转轮、使用电子元件的噪音、核裂变等等。这样的随机数生成器叫做物理性随机数生成器,它们的缺点是技术要求比较高。在实际应用中往往使用伪随机数就足够了。这些数列是“似乎”随机的数,实际上它们是通过一个固定的、可以重复的计算方法产生的。它们不真正地随机,因为它们实际上是可以计算出来的,但是它们具有类似于随机数的统计特征。这样的生成器叫做伪随机数生成器。在真正关键性的应用中,比如在密码学中,人们一般使用真正的随机数。

    1.Math.NET的其他随机数生成算法

      Math.NET在MathNet.Numerics.Random命名空间下包括了若干个其他随机数生成算法,基本介绍如下:

    1.Mcg31m1类 与 Mcg59 类,都属于 矩阵同余发生器,矩阵同余发生器是乘同余线性发生器的一个推广;2者的参数有些差别;

    3.MersenneTwister,Mersenne Twister算法译为马特赛特旋转演算法,是伪随机数发生器之一,其主要作用是生成伪随机数。此算法是Makoto Matsumoto (松本)和Takuji Nishimura (西村)于1997年开发的,基于有限二进制字段上的矩阵线性再生。可以快速产生高质量的伪随机数,修正了古老随机数产生算法的很多缺陷。 Mersenne Twister这个名字来自周期长度通常取Mersenne质数这样一个事实。常见的有两个变种Mersenne Twister MT19937和Mersenne Twister MT19937-64。Math.NET实现的版本是前者(Mersenne Twister MT19937)。介绍

    4.Mrg32k3a,又叫 素数模乘同余法,素数模乘同余发生器是提出的一个统计性质较好和周期较大的发生器,目前是使用最广的一种均匀随机数发生器下面给出两组经检验统计性质是良好的素数模乘同余发生器;

    5.Palf,是一个并行加法滞后的斐波那契伪随机数字生成器。

    6.WH1982与WH2006类,是乘线性同余法,也叫积式发生器,Math.NET实现的2个版本方便是1982和2006,代表作者发布该算法论文的2个时间,可以参考作者的2篇论文:

       1.Wichmann, B. A. & Hill, I. D. (1982), "Algorithm AS 183:An efficient and portable pseudo-random number generator". Applied Statistics 31 (1982) 188-190

      2. Wichmann, B. A. & Hill, I. D. (2006), "Generating good pseudo-random numbers".Computational Statistics & Data Analysis 51:3 (2006) 1614-1622

    8.Xorshift类,实现的是George Marsaglia,在论文“Xorshift RNGs”提出的一个算法,原理可以参考这篇论文:http://www.jstatsoft.org/v08/i14/paper

    2.Math.NET扩展随机数生成算法的实现

      上面已经已经对Math.NET扩展的几个随机数生成算法进行了介绍,对于一般人来说,直接用就可以了,但对于特殊的人来说,可能要用到其中一种,可以直接使用C#进行调用即可,当然为了节省大家的时间,这里对Math.NET的实现做一个简单的介绍,这样大家可以更加快速的扩展自己的算法,同时也可以了解实现的原理,对Math.NET有一个更加深入的了解。

       Math.NET对随机数的扩展也是借用了System.Random类,在它的基础上实现了一个随机数发生器的基类:RandomSource,所有的扩展算法都实现该类,这样使用RandomSource就非常方便。RandomSource的结构很简单,对System.Random进行了简单的封装,增加了几个直接生成其他类型随机数的方法,并都可以在继承中使用。其源码如下:  

      1  public abstract class RandomSource : System.Random
      2     {
      3         readonly bool _threadSafe;
      4         readonly object _lock = new object();
      5 
      6         /// <summary>
      7         /// Initializes a new instance of the <see cref="RandomSource"/> class using
      8         /// the value of <see cref="Control.ThreadSafeRandomNumberGenerators"/> to set whether
      9         /// the instance is thread safe or not.
     10         /// </summary>
     11         protected RandomSource() : base(RandomSeed.Robust())
     12         {
     13             _threadSafe = Control.ThreadSafeRandomNumberGenerators;
     14         }
     15 
     16         /// <summary>
     17         /// Initializes a new instance of the <see cref="RandomSource"/> class.
     18         /// </summary>
     19         /// <param name="threadSafe">if set to <c>true</c> , the class is thread safe.</param>
     20         /// <remarks>Thread safe instances are two and half times slower than non-thread
     21         /// safe classes.</remarks>
     22         protected RandomSource(bool threadSafe) : base(RandomSeed.Robust())
     23         {
     24             _threadSafe = threadSafe;
     25         }
     26 
     27         /// <summary>
     28         /// Fills an array with uniform random numbers greater than or equal to 0.0 and less than 1.0.
     29         /// </summary>
     30         /// <param name="values">The array to fill with random values.</param>
     31         public void NextDoubles(double[] values)
     32         {
     33             if (_threadSafe)
     34             {
     35                 lock (_lock)
     36                 {
     37                     for (var i = 0; i < values.Length; i++)
     38                     {
     39                         values[i] = DoSample();
     40                     }
     41                 }
     42             }
     43             else
     44             {
     45                 for (var i = 0; i < values.Length; i++)
     46                 {
     47                     values[i] = DoSample();
     48                 }
     49             }
     50         }
     51 
     52         /// <summary>
     53         /// Returns an infinite sequence of uniform random numbers greater than or equal to 0.0 and less than 1.0.
     54         /// </summary>
     55         public IEnumerable<double> NextDoubleSequence()
     56         {
     57             for (int i = 0; i < 64; i++)
     58             {
     59                 yield return NextDouble();
     60             }
     61 
     62             var buffer = new double[64];
     63             while (true)
     64             {
     65                 NextDoubles(buffer);
     66                 for (int i = 0; i < buffer.Length; i++)
     67                 {
     68                     yield return buffer[i];
     69                 }
     70             }
     71         }
     72 
     73         /// <summary>
     74         /// Returns a nonnegative random number.
     75         /// </summary>
     76         /// <returns>
     77         /// A 32-bit signed integer greater than or equal to zero and less than <see cref="F:System.Int32.MaxValue"/>.
     78         /// </returns>
     79         public override sealed int Next()
     80         {
     81             if (_threadSafe)
     82             {
     83                 lock (_lock)
     84                 {
     85                     return (int)(DoSample()*int.MaxValue);
     86                 }
     87             }
     88 
     89             return (int)(DoSample()*int.MaxValue);
     90         }
     91 
     92         /// <summary>
     93         /// Returns a random number less then a specified maximum.
     94         /// </summary>
     95         /// <param name="maxValue">The exclusive upper bound of the random number returned.</param>
     96         /// <returns>A 32-bit signed integer less than <paramref name="maxValue"/>.</returns>
     97         /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="maxValue"/> is negative. </exception>
     98         public override sealed int Next(int maxValue)
     99         {
    100             if (maxValue <= 0)
    101             {
    102                 throw new ArgumentException(Resources.ArgumentMustBePositive);
    103             }
    104 
    105             if (_threadSafe)
    106             {
    107                 lock (_lock)
    108                 {
    109                     return (int)(DoSample()*maxValue);
    110                 }
    111             }
    112 
    113             return (int)(DoSample()*maxValue);
    114         }
    115 
    116         /// <summary>
    117         /// Returns a random number within a specified range.
    118         /// </summary>
    119         /// <param name="minValue">The inclusive lower bound of the random number returned.</param>
    120         /// <param name="maxValue">The exclusive upper bound of the random number returned. <paramref name="maxValue"/> must be greater than or equal to <paramref name="minValue"/>.</param>
    121         /// <returns>
    122         /// A 32-bit signed integer greater than or equal to <paramref name="minValue"/> and less than <paramref name="maxValue"/>; that is, the range of return values includes <paramref name="minValue"/> but not <paramref name="maxValue"/>. If <paramref name="minValue"/> equals <paramref name="maxValue"/>, <paramref name="minValue"/> is returned.
    123         /// </returns>
    124         /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="minValue"/> is greater than <paramref name="maxValue"/>. </exception>
    125         public override sealed int Next(int minValue, int maxValue)
    126         {
    127             if (minValue > maxValue)
    128             {
    129                 throw new ArgumentException(Resources.ArgumentMinValueGreaterThanMaxValue);
    130             }
    131 
    132             if (_threadSafe)
    133             {
    134                 lock (_lock)
    135                 {
    136                     return (int)(DoSample()*(maxValue - minValue)) + minValue;
    137                 }
    138             }
    139 
    140             return (int)(DoSample()*(maxValue - minValue)) + minValue;
    141         }
    142 
    143         /// <summary>
    144         /// Fills an array with random numbers within a specified range.
    145         /// </summary>
    146         /// <param name="values">The array to fill with random values.</param>
    147         /// <param name="minValue">The inclusive lower bound of the random number returned.</param>
    148         /// <param name="maxValue">The exclusive upper bound of the random number returned. <paramref name="maxValue"/> must be greater than or equal to <paramref name="minValue"/>.</param>
    149         public void NextInt32s(int[] values, int minValue, int maxValue)
    150         {
    151             if (_threadSafe)
    152             {
    153                 lock (_lock)
    154                 {
    155                     for (var i = 0; i < values.Length; i++)
    156                     {
    157                         values[i] = (int)(DoSample()*(maxValue - minValue)) + minValue;
    158                     }
    159                 }
    160             }
    161             else
    162             {
    163                 for (var i = 0; i < values.Length; i++)
    164                 {
    165                     values[i] = (int)(DoSample()*(maxValue - minValue)) + minValue;
    166                 }
    167             }
    168         }
    169 
    170         /// <summary>
    171         /// Returns an infinite sequence of random numbers within a specified range.
    172         /// </summary>
    173         /// <param name="minValue">The inclusive lower bound of the random number returned.</param>
    174         /// <param name="maxValue">The exclusive upper bound of the random number returned. <paramref name="maxValue"/> must be greater than or equal to <paramref name="minValue"/>.</param>
    175         public IEnumerable<int> NextInt32Sequence(int minValue, int maxValue)
    176         {
    177             for (int i = 0; i < 64; i++)
    178             {
    179                 yield return Next(minValue, maxValue);
    180             }
    181 
    182             var buffer = new int[64];
    183             while (true)
    184             {
    185                 NextInt32s(buffer, minValue, maxValue);
    186                 for (int i = 0; i < buffer.Length; i++)
    187                 {
    188                     yield return buffer[i];
    189                 }
    190             }
    191         }
    192 
    193         /// <summary>
    194         /// Fills the elements of a specified array of bytes with random numbers.
    195         /// </summary>
    196         /// <param name="buffer">An array of bytes to contain random numbers.</param>
    197         /// <exception cref="T:System.ArgumentNullException"><paramref name="buffer"/> is null. </exception>
    198         public override void NextBytes(byte[] buffer)
    199         {
    200             if (buffer == null)
    201             {
    202                 throw new ArgumentNullException("buffer");
    203             }
    204 
    205             if (_threadSafe)
    206             {
    207                 lock (_lock)
    208                 {
    209                     for (var i = 0; i < buffer.Length; i++)
    210                     {
    211                         buffer[i] = (byte)(((int)(DoSample()*int.MaxValue))%256);
    212                     }
    213                 }
    214 
    215                 return;
    216             }
    217 
    218             for (var i = 0; i < buffer.Length; i++)
    219             {
    220                 buffer[i] = (byte)(((int)(DoSample()*int.MaxValue))%256);
    221             }
    222         }
    223 
    224         /// <summary>
    225         /// Returns a random number between 0.0 and 1.0.
    226         /// </summary>
    227         /// <returns>A double-precision floating point number greater than or equal to 0.0, and less than 1.0.</returns>
    228         protected override sealed double Sample()
    229         {
    230             if (_threadSafe)
    231             {
    232                 lock (_lock)
    233                 {
    234                     return DoSample();
    235                 }
    236             }
    237 
    238             return DoSample();
    239         }
    240 
    241         /// <summary>
    242         /// Returns a random number between 0.0 and 1.0.
    243         /// </summary>
    244         /// <returns>
    245         /// A double-precision floating point number greater than or equal to 0.0, and less than 1.0.
    246         /// </returns>
    247         protected abstract double DoSample();
    248     }
    View Code

      在扩展随机数生成算法的时候,直接继承该类即可,看一下Mcg59的实现源码:

      1 public class Mcg59 : RandomSource
      2     {
      3         const ulong Modulus = 576460752303423488;
      4         const ulong Multiplier = 302875106592253;
      5         const double Reciprocal = 1.0/Modulus;
      6         ulong _xn;
      7 
      8         /// <summary>
      9         /// Initializes a new instance of the <see cref="Mcg59"/> class using
     10         /// a seed based on time and unique GUIDs.
     11         /// </summary>
     12         public Mcg59() : this(RandomSeed.Robust())
     13         {
     14         }
     15 
     16         /// <summary>
     17         /// Initializes a new instance of the <see cref="Mcg59"/> class using
     18         /// a seed based on time and unique GUIDs.
     19         /// </summary>
     20         /// <param name="threadSafe">if set to <c>true</c> , the class is thread safe.</param>
     21         public Mcg59(bool threadSafe) : this(RandomSeed.Robust(), threadSafe)
     22         {
     23         }
     24 
     25         /// <summary>
     26         /// Initializes a new instance of the <see cref="Mcg59"/> class.
     27         /// </summary>
     28         /// <param name="seed">The seed value.</param>
     29         /// <remarks>If the seed value is zero, it is set to one. Uses the
     30         /// value of <see cref="Control.ThreadSafeRandomNumberGenerators"/> to
     31         /// set whether the instance is thread safe.</remarks>
     32         public Mcg59(int seed)
     33         {
     34             if (seed == 0)
     35             {
     36                 seed = 1;
     37             }
     38 
     39             _xn = (uint)seed%Modulus;
     40         }
     41 
     42         /// <summary>
     43         /// Initializes a new instance of the <see cref="Mcg59"/> class.
     44         /// </summary>
     45         /// <param name="seed">The seed value.</param>
     46         /// <remarks>The seed is set to 1, if the zero is used as the seed.</remarks>
     47         /// <param name="threadSafe">if set to <c>true</c> , the class is thread safe.</param>
     48         public Mcg59(int seed, bool threadSafe) : base(threadSafe)
     49         {
     50             if (seed == 0)
     51             {
     52                 seed = 1;
     53             }
     54 
     55             _xn = (uint)seed%Modulus;
     56         }
     57 
     58         /// <summary>
     59         /// Returns a random number between 0.0 and 1.0.
     60         /// </summary>
     61         /// <returns>
     62         /// A double-precision floating point number greater than or equal to 0.0, and less than 1.0.
     63         /// </returns>
     64         protected override sealed double DoSample()
     65         {
     66             double ret = _xn*Reciprocal;
     67             _xn = (_xn*Multiplier)%Modulus;
     68             return ret;
     69         }
     70 
     71         /// <summary>
     72         /// Fills an array with random numbers greater than or equal to 0.0 and less than 1.0.
     73         /// </summary>
     74         /// <remarks>Supports being called in parallel from multiple threads.</remarks>
     75         public static void Doubles(double[] values, int seed)
     76         {
     77             if (seed == 0)
     78             {
     79                 seed = 1;
     80             }
     81 
     82             ulong xn = (uint)seed%Modulus;
     83 
     84             for (int i = 0; i < values.Length; i++)
     85             {
     86                 values[i] = xn*Reciprocal;
     87                 xn = (xn*Multiplier)%Modulus;
     88             }
     89         }
     90 
     91         /// <summary>
     92         /// Returns an array of random numbers greater than or equal to 0.0 and less than 1.0.
     93         /// </summary>
     94         /// <remarks>Supports being called in parallel from multiple threads.</remarks>
     95         [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
     96         public static double[] Doubles(int length, int seed)
     97         {
     98             var data = new double[length];
     99             Doubles(data, seed);
    100             return data;
    101         }
    102 
    103         /// <summary>
    104         /// Returns an infinite sequence of random numbers greater than or equal to 0.0 and less than 1.0.
    105         /// </summary>
    106         /// <remarks>Supports being called in parallel from multiple threads, but the result must be enumerated from a single thread each.</remarks>
    107         public static IEnumerable<double> DoubleSequence(int seed)
    108         {
    109             if (seed == 0)
    110             {
    111                 seed = 1;
    112             }
    113 
    114             ulong xn = (uint)seed%Modulus;
    115 
    116             while (true)
    117             {
    118                 yield return xn*Reciprocal;
    119                 xn = (xn*Multiplier)%Modulus;
    120             }
    121         }
    122     }
    View Code

      随机数的使用大家都很熟练,和Random类差不多,上述扩展的算法中,也包括了很多 静态方法,可以直接使用。这里不再举例说明。

    3.资源

      源码下载:http://www.cnblogs.com/asxinyu/p/4264638.html

      如果本文资源或者显示有问题,请参考 本文原文地址http://www.cnblogs.com/asxinyu/p/4301555.html 

  • 相关阅读:
    postgresql 2012 大会PPT下载 Joe
    Postgresql连接 Joe
    查看Postgresql的连接数 Joe
    greta使用
    CString GetFileDir(const CString& csFile)
    UnicodeToAnsi函数
    myeclipse优化方案
    bool CreatedMultipleDirectory( char* direct)
    LPWSTR GBK(LPCSTR plszUtf8, WCHAR* lpszGBK)
    真正整合资源的高手
  • 原文地址:https://www.cnblogs.com/asxinyu/p/Dotnet_Opensource_MathNet_RandomGenerator_13.html
Copyright © 2011-2022 走看看