2015-10-20 20 views
1

我需要建立一個巴圖冊的是示出了由線性同餘法類用於在間隔計數數的頻率

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

main.cpp中:

int main() 
{ 
    LCG l; 
    l.countFrequency(); 
    l.printFrequency(); 
} 

它編譯和皮棉正確,但不希望運行。我不知道我的程序有什麼問題。函數countFrequency和printFrequency出錯。但我無法弄清楚什麼。也許你知道嗎?

+0

這是你的完整程序嗎?如果是這樣:你需要一個'main'函數。如果不是,你能澄清這個問題嗎?你如何編譯它?說「它不想跑」是什麼意思?當你嘗試運行它會發生什麼? –

+0

您是否嘗試過在調試器中運行?然後會發生什麼? –

+1

1.'頻率'的大小不正確,2.使用'double'而不是'float',3.溝渠那個析構函數。讓編譯器使用默認的。 – Bathsheba

回答

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
+0

非常感謝你!!!!! –