Boost C++ - generating a random real number betwee

2019-08-03 21:45发布

问题:

I've been reading the Boost C++ documentation and trying to figure out how to generate a random real number between 0 and 1, using the uniform_01 part of the library. Does anyone have any suggestions?

Based on suggestions, I'm using this code, but it generates the same random value every time.

double random01(mt19937 & generator)
{
    uniform_01<mt19937> dist(generator);
    return dist();
}

int main()
{
    mt19937 generator(time(0));
    for (int i = 0; i < 10; i++) {
        cout << random01(generator) << endl;
    }
    return 0;
}

Sorry if I wasn't clear; this question isn't solved, by my answer or any other. It's still generating the same random value each time.

回答1:

There are a few 'gotcha's in this code:

  1. The random01() function does not take a reference to the generator, but rather a copy of the generator. So if you call the function multiple times with the same generator - it will produce the same value over and over again!
  2. The static uniform_01 in random01() only gets initialized on the first call to random01, so if it is ever called with a different generator, it will not use it, but rather use a reference to the first generator, which may even have been destroyed, since!

Correct would be something like following (note the & in the arguments list, for pass-by-reference, and the lack of static:

double random01(mt19937 & generator)
{
    uniform_01<mt19937> dist(generator);
    return dist();
}


回答2:

This is the solution I found:

#include <iostream>
#include <ctime>
#include <boost/random.hpp>

using std::cout;
using std::endl;

using boost::mt19937;
using boost::uniform_01;

double random01(mt19937 generator)
{
    static uniform_01<mt19937> dist(generator);
    return dist();
}

int main()
{
    mt19937 generator(time(0));
    cout << random01(generator) << endl;

}

The code is slightly modified from here; hat tip to Bojan Nikolic.

I posted this as a "solution" in the hope that it helps someone, but please criticise anything you notice wrong with it. I tried to separate the seeding step from the actual generation so the twister isn't seeded every single time it generates a value.



标签: c++ boost random