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
rng1.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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With