0

I'm trying to make a model of a zombie apocalipse in c++ using simple structs and a when I'm randomizing the population, I need some fields of the struct to have a value in the interval [0..1[. As I'm interested in a more statistically correct analysis, I choose to use the mt19937 engine to generate my "data". When playing around with this PRNG I couldn't find a way to generate a number in said range. Here's the code that I came up with:

int
main ( int argc, char** argv )
{

    mt19937_64 newr ( time ( NULL ) );
    std::cout << newr.max ( ) << endl;
    std::cout << newr.min ( );
    double rn;
    for(;;){
        rn = newr()/newr.max ();
        std::cout << rn << std::endl;
    }
}

But the only outputs that I get for the loop are zeros (0). A small print of the output is down:

18446744073709551615
0
0
0
0
0
0
0
0
0
0
0

Any ideas?

4

2 回答 2

3

This happens because the return value of newr() and newr.max() are integers and the value returned by newr() is smaller than newr.mar(). The result of the division is a zero integer which is then converted to a double. To fix this use

rn = static_cast<double>(newr()) / newr.max();
于 2014-12-30T23:27:41.940 回答
3

You divide int by int and so have integer rounding.

A way to use the random engine is by one of the various distributions, in your case std::uniform_real_distribution:

std::mt19937_64 engine ( time ( NULL ) );
std::uniform_real_distribution<double> dist(0., 1.);
for(;;){
    const double rn = dist(engine);
    std::cout << rn << std::endl;
}
于 2014-12-31T00:34:39.870 回答