用于计算间隔中数字频率的类

时间:2015-10-20 11:14:38

标签: c++ frequency frequency-distribution

我需要建立一个条形图,用于说明通过线性同余方法确定的伪随机数的分布

INT IDENTITY
区间[0,1]

上的

例如: 区间频率

Xn+1 = (a * Xn + c) mod m
U = X/m

我写过这样的程序

lcg.h:

[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.cpp:

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;
};

main.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;
    }
}

它正确编译和lint,但不想运行。我不知道我的程序有什么问题。函数countFrequency和printFrequency出错了。但我无法弄清楚是什么。也许你知道吗?

1 个答案:

答案 0 :(得分:2)

这部分错了:

for (int i = 0; i < m; ++i)
    frequencies[i] = 0;

此时你的frequencies是空的,你无法访问它的元素:索引超出界限,导致崩溃。要填充矢量,请使用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
相关问题