Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating two independent random number sequences (C++)

Tags:

c++

random

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

like image 493
Neal Avatar asked Jul 25 '10 14:07

Neal


2 Answers

Use rand_r.

like image 75
Marcelo Cantos Avatar answered Sep 22 '22 18:09

Marcelo Cantos


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;
}
like image 7
kennytm Avatar answered Sep 24 '22 18:09

kennytm