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 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.