C++程序来实现线性同余发生器以进行伪随机数生成


线性同余发生器是一个非常简单的随机数发生器示例。它是历史最悠久、最著名的伪随机数生成算法之一。该方法中使用 −

Xn+1=(aXn + C) mod m

其中 X 是伪随机值的序列,并且

m,0<m— the “modulus"
a,0<a<m — the "multiplier"
c,0<c<m — the "increment"
X0, 0<x0<m — the "seed" or "start value"

是指定生成器的整数常量。

此方法的一个好处是,通过适当选择参数,可以知道且较长的周期。

算法

Begin
   Declare class mRND
   Create a function Seed(number)
      Assign a variable _seed=number
      Create a constructor mRND
   Declare _seed(0), a(0), c(0), m(2147483648)
   Create a function rnd()
      Return
         _seed = (a * _seed + c) mod m
      Declare a, c, m, _seed
   Done
   Declare an another subclass MS_RND inheriting from base class mRND
   Create a constructor
      Read the variables a, c
      Create a function rnd()
      return mRND::rnd() right shift 16
   Done
   Declare an another subclass BSD_RND inheriting from base class mRND
   Create a constructor
      Read the variables a, c
      Create a function rnd()
      return mRND::rnd()
   Done
   For x=0 to 6
      Print MS_RAND
   For x=0 to 6
      Print BSD_RAND
   Done
End

示例代码

#include <iostream>
using namespace std;
class mRND {
   public:
   void seed(unsigned int s) {
      _seed= s;
   }
   protected:
   mRND() :
   _seed(0), a(0), c(0), m(2147483648) { }
   int rnd() {
      return (_seed = (a * _seed + c) % m);
   }
   int a, c;
   unsigned int m, _seed;
};
class MS_RND: public mRND {
   public:
   MS_RND() {
      a = 214013;
      c = 2531011;
   }
   int rnd() {
      return mRND::rnd() >> 16;
   }
};
class BSD_RND: public mRND {
   public:
   BSD_RND() {
      a = 1016404597;
      c = 12345;
   }
   int rnd() {
      return mRND::rnd();
   }
};
int main(int argc, char* argv[]) {
   BSD_RND bsd_rnd;
   MS_RND ms_rnd;
   cout << "MS RAND:" << endl << "-----------" << endl;
   for (int x = 0; x < 6; x++)
      cout << ms_rnd.rnd() << endl;
   cout << endl << "BSD RAND:" << endl << "-------------" << endl;
   for (int x = 0; x < 6; x++)
      cout << bsd_rnd.rnd() << endl;
      return 0;
}

输出

MS RAND:
-------
38
7719
21238
2437
8855
11797
BSD RAND:
--------
12345
1915290694
1005338679
629284700
741596485
1834373826

更新于: 2019 年 7 月 30 日

996 次浏览

开启你的职业生涯

通过完成课程获得认证

立即开始
广告