views:

130

answers:

5

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++?

+8  A: 

Use rand_r.

Marcelo Cantos
A: 

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.

Rin
@Rin: This would be better left as a comment, not an answer.
indiv
+6  A: 

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;
}
KennyTM
+1 for the (soon-to-be-)standard solution.
James McNellis
+2  A: 

You could also use Boost.Random.

More technical documentation here.

aib
A: 

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.