out of range random number generation in C++ using tr1

假装没事ソ 提交于 2019-12-24 02:27:33

问题


I am trying to generate number from a uniform distribution of real number in the range of [0, 1). But compiler is generating numbers which are out of [0, 1) range.

Here is the code:

int main(void) {
    // Solver solve;

    mt19937 mteng;
    mteng.seed(rdtsc());
    uniform_real<double> uniRealD;

    double randomNum;

    for (int index = 0; index < 10; index++){
        randomNum = uniRealD(mteng);

        if(randomNum<0.5)
            cout<<index<<" no. random number is: "<<randomNum<<endl;
        else
            cout<<"number generate is not in range"<<endl;
    }

    return 0;
}

Any comments on what could be wrong with the code? I am using rdtsc() as seed.


回答1:


I had to get rid of your seed function, rdtsc(), make some includes, introduce a using namespace std, and change a 0.5 to 1.0, and change uniform_real to uniform_real_distribution, but after that, using libc++, I get:

#include <random>
#include <iostream>

using namespace std;

int main(void) {
    // Solver solve;

    mt19937 mteng;
    mteng.seed(0);
    uniform_real_distribution<double> uniRealD;

    double randomNum;

    for (int index = 0; index < 10; index++){
        randomNum = uniRealD(mteng);

        if(randomNum<1.0)
            cout<<index<<" no. random number is: "<<randomNum<<endl;
        else
            cout<<"number generate is not in range"<<endl;
    }

    return 0;
}

0 no. random number is: 0.592845
1 no. random number is: 0.844266
2 no. random number is: 0.857946
3 no. random number is: 0.847252
4 no. random number is: 0.623564
5 no. random number is: 0.384382
6 no. random number is: 0.297535
7 no. random number is: 0.056713
8 no. random number is: 0.272656
9 no. random number is: 0.477665



回答2:


Your code shouldn't be doing that. Probably a bug in the implementation. What compiler and library versions? Try moving away from tr1 to C++11.




回答3:


    if(randomNum<0.5)
        cout<<index<<" no. random number is: "<<randomNum<<endl;
    else
        cout<<"number generate is not in range"<<endl;

Change the if statement to if(randomNum < 1.)



来源:https://stackoverflow.com/questions/10133832/out-of-range-random-number-generation-in-c-using-tr1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!