0

I need to implement a good RNG and I guess Mersenne Twister could be good for me. I didn't find anywhere a working C++ implementation, am I a bad google searcher or is it really not simple to find?! I've tried before rand():

srand((unsigned)time(0));
for (int i = 0; i < 9; i++) {
     random =  rand();
     cout<<random;
}

I don't know why, but the random variable is always the same number.....BUT if I add a Sleep(1000), it works! Like this:

srand((unsigned)time(0));
for (int i = 0; i < 9; i++) {
    random =  rand();
    cout<<random;
    Sleep(1000);
}

So I decided to try Mersenne Twister...Could someone find a solution of this (because I need to find a very very big number of random numbers so I can't use Sleep(1000), it would takes eras!) or help me to implement Mersenne Twister or maybe also another good RNG. Thanks and sorry for my bad English...

6

2 Answers 2

7

C++11 includes a mersenne twister with the random standard library header.

1

Boost.Random is an available implementation, if your STL implementation doesn't have it.

You can use random_device to get a random seed, and then pass it to the mt19937 constructor to initialize the random number generator.
Then you can use uniform_int_distribution to get a random integer, uniformly distributed in the closed range [a, b] that you specify in uniform_int_distribution constructor.

You may want to consider this sample code (compiled with g++ 4.8.1):

#include <iostream>
#include <boost\nondet_random.hpp>
#include <boost\random.hpp>

int main() {        
    // Get a random seed
    boost::random_device rd;
    const auto seed = rd();

    // Marsenne Twister generator
    boost::random::mt19937 mt(seed);

    // Get random integers uniformly distributed in range [0, 99]
    boost::random::uniform_int_distribution<int> dist(0, 99);

    // Print 10 random numbers, uniformly distributed in previous range
    for (int i = 0; i < 10; ++i) {
        std::cout << dist(mt) << " ";
    }
    std::cout << std::endl;    
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.