23

The new C++11 Standard has a whole chapter dedicated to random number generators. But how do I perform the simplest, most common task that used to be coded like this, but without resorting to the standard C library:

srand((unsigned int)time(0)); int i = rand();

Are there reasonable defaults for random-number engines, distributions, and seeds that one could use out of the box?

11
  • Wikipedia? en.wikipedia.org/wiki/… Commented Aug 27, 2011 at 22:31
  • 2
    What's wrong with the code you have? AFAIK, the new random number generators were added for more "serious" applications where the aspects of the random number generation really matter. Commented Aug 27, 2011 at 22:33
  • 3
    @GMan: To be fair, several of the random number engines in the new standard could be described as simple and fast and I wouldn't view them as particularly "serious". Commented Aug 27, 2011 at 22:57
  • 6
    Every time I use standard C library inside C++ I feel like I'm doing something unseemly. And look at the cast! There has to be a better way. Commented Aug 27, 2011 at 23:08
  • 1
    @Charles Bailey I'm not sure either! You're right, only rand is part of standard C, and random is part of POSIX and arc4random is provided in BSD. Commented Aug 28, 2011 at 16:24

7 Answers 7

30

You should be able to do something like:

std::default_random_engine e((unsigned int)time(0)); int i = e(); 

The quality of the default_random_engine is implementation dependent. You could also use std::min_rand0 or std::min_rand.

Probably a better way to seed a random engine is with as true a random number as is available from the implementation rather than use time.

E.g.

std::random_device rd; std::default_random_engine e( rd() ); 
Sign up to request clarification or add additional context in comments.

8 Comments

To clarify, do you mean "should" as in "this doesn't exist but it ought to" or sd "this exists and your compiler ought to support it"?
Informational: The biggest difference between this answer and the OP's example is that the coder controls where the engine's state is: It is in e. In the OP's code the state is hidden as static data inside rand. This is an important difference when dealing with multithreaded programs. rand has to have some kind of protection to make it thread safe. default_random_engine doesn't. If you want to call it from multiple threads, you provide the synchronization mechanism yourself, externally. This means default_random_engine can be faster if you don't need to synchronize it.
@Charles: I just tested your code on libc++. Given the proper includes, it works. One might need std:: on time <shrug>. std::default_random_engine is required by conforming hosted C++11 platforms. On libc++ it is equivalent to minstd_rand which is a linear_congruential_engine.
@Howard: What about seeding? Is there a default in the Standard to seed a random number generator using some implementation dependent magic? Or is time(0) still the only practical and portable way? I'm not using random numbers for anything fancy like encryption -- just to randomize my tests.
@Bartosz: I rather like Charles' random_device suggestion if you don't need or want repeatability in the random sequence. Or you can continue using time. Or there is this thing called seed_seq which is a souped-up seeder on steroids. I've implemented the thing and am still not quite sure when to use it. :-) And for extra fun, seed_seq itself can be seeded!
|
6

Unifying and simplifying some of the samples already provided I will summarize to:

// Good random seed, good engine auto rnd1 = std::mt19937(std::random_device{}()); // Good random seed, default engine auto rnd2 = std::default_random_engine(std::random_device{}()); // like rnd1, but force distribution to int32_t range auto rnd3 = std::bind(std::uniform_int_distribution<int32_t>{}, std::mt19937(std::random_device{}())); // like rnd3, but force distribution across negative numbers as well auto rnd4 = std::bind(std::uniform_int_distribution<int32_t>{std::numeric_limits<int32_t>::min(),std::numeric_limits<int32_t>::max()}, std::mt19937(std::random_device{}())); 

Then I ran some tests to see what the defaults look like:

#include <random> #include <functional> #include <limits> #include <iostream> template<class Func> void print_min_mean_max(Func f) { typedef decltype(f()) ret_t; ret_t min = std::numeric_limits<ret_t>::max(), max = std::numeric_limits<ret_t>::min(); uint64_t total = 0, count = 10000000; for (uint64_t i = 0; i < count; ++i) { auto res = f(); min = std::min(min,res); max = std::max(max,res); total += res; } std::cout << "min: " << min << " mean: " << (total/count) << " max: " << max << std::endl; } int main() { auto rnd1 = std::mt19937(std::random_device{}()); auto rnd2 = std::default_random_engine(std::random_device{}()); auto rnd3 = std::bind(std::uniform_int_distribution<int32_t>{}, std::mt19937(std::random_device{}())); auto rnd4 = std::bind(std::uniform_int_distribution<int32_t>{std::numeric_limits<int32_t>::min(),std::numeric_limits<int32_t>::max()}, std::mt19937(std::random_device{}())); print_min_mean_max(rnd1); print_min_mean_max(rnd2); print_min_mean_max(rnd3); print_min_mean_max(rnd4); } 

Produces the output:

min: 234 mean: 2147328297 max: 4294966759 min: 349 mean: 1073305503 max: 2147483423 min: 601 mean: 1073779123 max: 2147483022 min: -2147481965 mean: 178496 max: 2147482978 

So as we can see, mt19937 and default_random_engine have a different default range, so use of uniform_int_distribution is advised.

Also, default uniform_int_distribution is [0, max_int] (non-negative), even when using a signed integer type. Must provide range explicitly if you want full range.

Finally, its important to remember this at times like these.

2 Comments

Of note, there is a 64 bit version of std::mt19937: std::mt19937_64 that returns 64 bits of randomness per call. auto rnd5 = std::mt19937_64(std::random_device{}()); // min: 4879020137534 mean: 1655417118684 max: 18446741225191893648
By the way, is it safe to re-use the same random number engine with many distributions and std::bind() or is it better to bind each distribution to a new engine instance? How's this: std::mt19937_64 random = std::mt19937_64(std::random_device{}()); auto randomCardinality = std::bind(std::uniform_int_distribution<int>(1, 4), random); auto randomValue = std::bind(std::uniform_real_distribution<double>(-1.0, 1.0), random);
2

If your existing code was appropriate before the new standard, then it will continue to be. The new random number generators were added for applications which require a higher quality of pseudo-randomness, e.g. stochastic simulation.

Comments

2

I use the following code in my project. 'engine' and 'distribution' can be one of the provided by the library.

#include <random> #include <functional> #include <iostream> ... std::uniform_int_distribution<unsigned int> unif; std::random_device rd; std::mt19937 engine(rd()); std::function<unsigned int()> rnd = std::bind(unif, engine); std::cout << rnd() << '\n'; 

Comments

2

Here you go. Random doubles in a range:

// For ints // replace _real_ with _int_, // <double> with <int> and use integer constants #include <random> #include <iostream> #include <ctime> #include <algorithm> #include <iterator> int main() { std::default_random_engine rng(std::random_device{}()); std::uniform_real_distribution<double> dist(-100, 100); //(min, max) //get one const double random_num = dist(rng); //or.. //print 10 of them, for fun. std::generate_n( std::ostream_iterator<double>(std::cout, "\n"), 10, [&]{ return dist(rng);} ); return 0; } 

Comments

0

Random number generation is a difficult problem. There is no truly random way to do it. If you are just generating randomness to seed a game environment then your approach should be fine. rand() has several shortcomings.

If you are needing randomness to generate encryption keys then you're S.O.L. The best way in that case is to go out to the operating system, which usually has mechanism. On POSIX that's random() (or read from /dev/random if you're so disposed). On Windows you can use the CryptoAPI:

https://www.securecoding.cert.org/confluence/display/seccode/MSC30-C.+Do+not+use+the+rand%28%29+function+for+generating+pseudorandom+numbers

Comments

0

You could use RC4 to generate random bytes. This probably has the properties that you want. It is fast and fairly simple to implement. The sequence is repeatable across all implementations when the seed is known, and completely unpredictable when the seed is not known. http://en.wikipedia.org/wiki/RC4

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.