선형 합동 생성기는 난수 생성기의 매우 간단한 예입니다. 가장 오래되고 가장 잘 알려진 의사 난수 생성기 알고리즘 중 하나입니다. 이 메소드에서 사용되는 함수 -
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