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

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

[singlepic=18395]

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

算法实现

[code=’cpp’]
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;
};
[/code]

[code=’cpp’]
#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;
}
[/code]

测试代码

[code=’cpp’]
RandomFactory *random = new RandomFactory();
int *statistics = new int[10];
for(long i = 0; i < 10; ++i) { statistics[i] = 0; } for(long i = 0; i < 1000; ++i) { int thisRandom = random->LinerCongruentialRandom();
statistics[thisRandom]++;
//cout<<"["<计算结果

[code=’sh’]
[0]:94
[1]:114
[2]:105
[3]:90
[4]:98
[5]:101
[6]:91
[7]:105
[8]:91
[9]:111
[/code]

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

发表评论