线性同余生成器是随机数生成器的非常简单的示例。它是最古老和最著名的伪随机数生成器算法之一。此方法中使用的功能-
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