boost::random generate the same number every time

放肆的年华 提交于 2019-12-01 03:20:06

if you want the sequence of random numbers to change every time you run your program, you need to change the random seed by initializing it with the current time for instance

you will find an example there, excerpt:

/*
 * Change seed to something else.
 *
 * Caveat: std::time(0) is not a very good truly-random seed.  When
 * called in rapid succession, it could return the same values, and
 * thus the same random number sequences could ensue.  If not the same
 * values are returned, the values differ only slightly in the
 * lowest bits.  A linear congruential generator with a small factor
 * wrapped in a uniform_smallint (see experiment) will produce the same
 * values for the first few iterations.   This is because uniform_smallint
 * takes only the highest bits of the generator, and the generator itself
 * needs a few iterations to spread the initial entropy from the lowest bits
 * to the whole state.
 */
generator.seed(static_cast<unsigned int>(std::time(0)));

You need to seed your random number generator so it doesn't start from the same place each time.

Depending on what you are doing with the numbers, you may need to put some thought into how you choose your seed value. If you need high quality randomness (if you are generating cryptographic keys and want them fairly secure), you will need a good seed value. If this were Posix, I would suggest /dev/random - but you look to be using Windows so I'm not sure what a good seed source would be.

But if you don't mind a predictable seed (for games, simulations, etc.), a quick and dirty seed is the current timestamp returned by time().

Chris Huang-Leaver

If you are running on a 'nix system, you could always try something like this;

int getSeed()
{
    ifstream rand("/dev/urandom");
    char tmp[sizeof(int)];
    rand.read(tmp,sizeof(int));
    rand.close();
    int* number = reinterpret_cast<int*>(tmp);
    return (*number);
}

I'm guessing seeding the random number generator this way is faster than simply reading the /dev/urandom (or /dev/random) for all your random number needs.

You can use the boost::random::random_device class either as-is, or to seed your other generator.

You can get a one-off random number out of it with a simple:

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