我需要构建一个条形图来说明由线性同余法确定的伪随机数的分布
Xn+1 = (a * Xn + c) mod m
U = X/m
在区间[0,1]上
例如: 间隔频率
[0;0,1] 0,05
[0,1;0,2] 0,15
[0,2;0,3] 0,1
[0,3;0,4] 0,12
[0,4;0,5] 0,1
[0,5;0,6] 0,15
[0,6;0,7] 0,05
[0,7;0,8] 0,08
[0,8;0,9] 0,16
[0,9;1,0] 0,4
我写过这样的程序
lcg.h:
class LCG {
public:
LCG();
~LCG();
void setSeed(long);
float getNextRand();
void countFrequency();
void printFrequency();
private:
vector<int>frequencies;
long seed;
static const long a = 33;
static const long c = 61;
static const long m = 437;
};
lcg.cpp:
void LCG::setSeed(long newSeed)
{
seed = newSeed;
}
LCG::LCG() {
setSeed(1);
}
LCG::~LCG() { }
float LCG::getNextRand() {
seed = (seed * a + c) % m;
return (float)seed / (float)m;
}
void LCG::countFrequency()
{
for (int i = 0; i < 10; ++i)
frequencies[i] = 0;
for (int i = 0; i < m; ++i)
{
float u = getNextRand();
int r = ceil(u * 10.0);
frequencies[r] = frequencies[r] + 1;
}
}
void LCG::printFrequency()
{
for (int i = 0; i < 10; ++i)
{
const float rangeMin = (float)i / 10.0;
const float rangeMax = (float)(i + 1) / 10.0;
cout << "[" << rangeMin << ";" << rangeMax << "]"
<< " | " << frequencies[i] << endl;
}
}
主要.cpp:
int main()
{
LCG l;
l.countFrequency();
l.printFrequency();
}
它可以正确编译和 lint,但不想运行。我不知道我的程序有什么问题。函数 countFrequency 和 printFrequency 有问题。但我不知道是什么。也许你知道?
最佳答案
这部分是错误的:
for (int i = 0; i < m; ++i)
frequencies[i] = 0;
此时你的 frequencies
是空的,你不能像这样访问它的元素:索引越界,这导致了崩溃。要填充 vector ,请使用 push_back()
:
for (int i = 0; i < m; ++i)
frequencies.push_back(0);
其他小东西:
你的构造函数做了太多的工作:
LCG::LCG() { setSeed(1); }
正确的方法是使用初始化列表:
LCG::LCG() : seed(1){ }
如果您在析构函数中没有做任何特殊的事情,根本就不要定义它,让编译器为您做。
- 使用
double
而不是float
以获得更高的精度;ceil
无论如何都会操作double
。
关于c++ - 计算区间内数字频率的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33235189/