Generating two independent random number sequences (C++)
I'd like to be able to do something like this (obviously not valid C++):
rng1 = srand(x)
rng2 = srand(y)
//rng1 and rng2 give me two separate sequences of random numbers
//based on the srand seed
rn开发者_如何学JAVAg1.rand()
rng2.rand()
Is there any way to do something like this in C++? For example in Java I can create two java.util.Random objects with the seeds I want. It seems there is only a single global random number generator in C++. I'm sure there are libraries that provide this functionality, but anyway to do it with just C++?
Use rand_r.
In TR1 (and C++0x), you could use the tr1/random
header. It should be built-in for modern C++ compilers (at least for g++ and MSVC).
#include <tr1/random>
// use #include <random> on MSVC
#include <iostream>
int main() {
std::tr1::mt19937 m1 (1234); // <-- seed x
std::tr1::mt19937 m2 (5678); // <-- seed y
std::tr1::uniform_int<int> distr(0, 100);
for (int i = 0; i < 20; ++ i) {
std::cout << distr(m1) << "," << distr(m2) << std::endl;
}
return 0;
}
You could also use Boost.Random.
More technical documentation here.
I just want to point out, that using different seeds may not give you statistically independent random sequences. mt19937 is an exception. Two mt19937 objects initialized with different seeds will give you more or less (depending whom you ask) statistically independent sequences with very high probability (there is a small chance that the sequences will overlap). Java's standard RNG is notoriously bad. There are plenty of implementations of mt19937 for Java, which should be preferred over the stock RNG.
as @James McNellis said, I can't imagine why do you would do that, and what pros you will get. Describe what effect you would like to achieve.
For whatever reason, the following generators interfere with each other. I need two independent generators for a task and need to reconstruct the streams. I haven't dug into the code but the std::tr1 and C++11 generators seem to share states in common. Adding m2 below changes what m1 will deliver.
std::tr1::mt19937 m1 (1234); // <-- seed x
std::tr1::mt19937 m2 (5678); // <-- seed y
I had to build my own to ensure independence.
精彩评论