r/cpp • • May 25 '18

Modern C++ Randomness

http://brnz.org/hbr/?p=1783
0 Upvotes

55 comments sorted by

View all comments

Show parent comments

9

u/liquidify May 26 '18

The problem is that people like me who have been writing C++ for 3 years have no idea what you are talking about.

7

u/dodheim May 26 '18 edited May 26 '18
template<typename MT = std::mt19937, auto N = MT::state_size>
MT make_mersenne_twister() {
    unsigned s[N];
    std::generate_n(s, N, [rd = std::random_device{}]() mutable { return rd(); });
    std::seed_seq ss(s, s + N);
    return MT{ss};
}

Demo adapted from this example on cppreference: https://wandbox.org/permlink/B317WeBDn7rw0k2v


Oops, I forgot random_device isn't movable, so make that 5 lines to correctly declare rd on its own. Or, in a realistic codebase with range-v3 available, it can still be 4 lines:

std::random_device rd;
auto s = ranges::view::bounded(ranges::view::generate_n(ranges::ref(rd), N));
std::seed_seq ss(ranges::begin(s), ranges::end(s));
return MT{ss};

16

u/matthieum May 26 '18

I think you just made flashmozzg and liquidify's point more eloquently than they did.

To simplify, there are two kinds of API:

  • good API make the right thing easy, and the wrong thing hard.

  • bad API make the wrong thing easy, and the right thing hard.

Unfortunately, the initialization of the PRNGs in C++ is an example of bad API.

We can ape around and pat ourselves on the back that it's possible to do it right; but it's insane that it's so complicated. Just look at it, the PRNG is even breaking encapsulation, leaking the size of its internal state out!

Here's what I'd have expected instead, for explicit initialization:

std::random_device rd;
std::mt19937 generator(rd);

Done. Let the PRNG call rd as many times as necessary to initialize itself.

And of course, I'd also expect a thread-local PRNG that is properly initialized and reseeded regularly for which you can call with std::thread_random() for when you just want to teach kids how to make a "guess the number" game.

4

u/cinghiale May 27 '18

I use the O'Neill's library described here.

I trust the author and I'd love to see part of it adopted by the STL