Skip to content

全周期线性同余随机数生成器

全周期线性同余随机数生成器(Full period linear congruential random generator):

其中如果前两项的和为非负数,则δ(Xi)=0,否则δ(Xi)=1。 研究发现取素数M=2147483647,A=48271可以取得不错的随机性。鉴于这样的取值被仔细研究过并广泛应用,因此一般不要改这两个取值。

算法实现

class RandomFactory
{
public:
	RandomFactory();
	long LinerCongruentialRandom();
private:
	static const long A = 48271;
	static const long M = 2147483647;
	static const long Q = M / A;
	static const long R = M % A;
	long lastValue;
};
#include "stdafx.h"
RandomFactory::RandomFactory()
{
	this->lastValue = 1;
}

long RandomFactory::LinerCongruentialRandom()
{
	long temp = this->A * (this->lastValue % this->Q) -
				R * (this->lastValue / this->Q);
	if(temp < 0)
	{
		temp += this->M;
	}
	this->lastValue = temp;
	return temp % 10;
}

测试代码

RandomFactory *random = new RandomFactory();
int *statistics = new int;
for(long i = 0; i < 10; ++i)
{
	statistics = 0;
}

for(long i = 0; i < 1000; ++i)
{
	int thisRandom = random->LinerCongruentialRandom();
	statistics++;
	//cout<<"["<<i<<"]:"<<thisRandom<<endl;
}

for(long i = 0; i < 10; ++i)
{
	cout<<"["<<i<<"]:"<<statistics<<endl;
}

计算结果

:94
:114
:105
:90
:98
:101
:91
:105
:91
:111

我们还是可以发现不错的随机性。