2

我正在尝试从 [0, 1) 范围内的实数均匀分布中生成数字。但是编译器正在生成超出 [0, 1) 范围的数字。

这是代码:

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

关于代码可能有什么问题的任何评论?我rdtsc()用作种子。

4

3 回答 3

2

你的代码不应该那样做。可能是实现中的一个错误。什么编译器和库版本?尝试从 tr1 迁移到 C++11。

于 2012-04-13T01:09:07.850 回答
2

我不得不去掉你的种子函数,rdtsc()做一些包含,引入 a using namespace std,并将 a 0.5 更改为 1.0,然后更改uniform_realuniform_real_distribution,但在那之后,使用 libc++,我得到:

#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
于 2012-04-13T01:22:11.910 回答
1
    if(randomNum<0.5)
        cout<<index<<" no. random number is: "<<randomNum<<endl;
    else
        cout<<"number generate is not in range"<<endl;

if将语句更改为if(randomNum < 1.)

于 2012-04-13T00:44:29.427 回答