Search code examples
c++randomprngmersenne-twister

Random real in [0..1[ using Mersenne Twister


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?


Solution

  • 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();