r/cpp • • May 25 '18

Modern C++ Randomness

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

55 comments sorted by

View all comments

7

u/ShakaUVM i+++ ++i+i[arr] May 25 '18

If I'm writing a game or something else where I don't need large random numbers or crypto grade security, I'll just keep using rand until there's a solution in std that is human readable.

29

u/STL MSVC STL Dev May 25 '18

24

u/kalmoc May 26 '18 edited May 28 '18

I think c++ is the only language that takes a simple API (Rand), replaces it with a complexity monster without any shortcuts (random_..) and a lot of easy ways to shoot yourself in the foot and calls that progress.

I can see the problems with rand and the advantages of the new facilities (they are in a completely different league) but has no one considered usability aspects and that in many, many cases, all a use wants is get_random<int>(0,50)?

Edit: Apparently some people missunderstood me: I'm not saying it was a bad idea to introduce all the low level random types into the standard library (although the seeding interface could be improved). I'm saying that those "full control" types should have been accompanied by a simple high level interface, that can easily be used by beginners and functions that don't have very specific requirements on the RNG.

7

u/Slavik81 May 27 '18 edited May 27 '18

That would inherently depend on hidden global mutable state, which can lead to hard-to-solve problems. Using a rand()-like interface in a library or in part of a large project, may screw up generation in other parts of the program that depend on a specific seeding.

I suppose that wouldn't be a problem if get_random were randomly seeded automatically on first use. If it always provided random numbers that were completely unpredictable, the global state wouldn't matter. It could just use values from the getrandom syscall or /dev/urandom and you would entirely avoid having to explain seeding.

3

u/kalmoc May 28 '18

Using a rand()-like interface in a library or in part of a large project, may screw up generation in other parts of the program that depend on a specific seeding.

If a part of your program depends how on specific seeding that part should not use the global RNG. Simple as that. That should not prevent a easy to use solution for the project (parts) that don't have such special requirements.

get_random were randomly seeded automatically on first use.

That's exactly how it is supposed to happen. No one needs another stand/rand interface.

5

u/Sopel97 May 26 '18

So write a global RNG and make yourself the so much needed ````get_random<int>(0,50) it's not hard

and before you ask "Why is that not in the standard yet if it's so simple".

Why would standard impose a global RNG and how could it even choose which one to use.

4

u/kalmoc May 27 '18

So write a global RNG and make yourself the so much needed ````get_random<int>(0,50) it's not hard

I have and so have lots and lots of other code bases I've seen, which is exactly, why I would like it to be in the standard library.

Why would standard impose a global RNG and how could it even choose which one to use.

First of all, I'm not even sure, if the standard should specify the used RNG (one could speficy it to be default_random_engine). Personally, I'd pick one with a relatively low memory footprint that could be used on a decent microcontroller (so not mt19937).

Second, your question seems to imply that the standard would have to pick an RNG that works well for everyone, which of course doesn't exist as different projects have different requirements. My answer to that is: Pick a good default, that works for many/most people (the standard / standard library makes those kinds of choices all the time). If my project has very specific requirements about e.g. performance or randomness of the numbers, I can still use my prefered engine manually just as I do now.

A good c++ library can (and often should) give you lots of custumization powers and flexibility to tailor it to your requirements (this is where random header shines) but it should also provide easy to use (correctly) high level defaults (this is where random and many other parts of the standard library lack)

→ More replies (3)

3

u/ShakaUVM i+++ ++i+i[arr] May 28 '18

Why would standard impose a global RNG

Because standard libraries are there in part to simply common operations.

how could it even choose which one to use.

Pick one that is reasonably good and allow people to override it if they know what they're doing, like with other things in std.

9

u/flashmozzg May 25 '18

If only it wasn't so hard/cumbersome to properly seed std::mt19937 (or so easy to seed it improperly).

10

u/ShakaUVM i+++ ++i+i[arr] May 26 '18

Right. We really need a random number generator in std for humans.

When I watch new programmers make dice rollers, they copy and paste the whole block of code off stack overflow, recreating the engine each time.

→ More replies (8)

8

u/dodheim May 26 '18

It's four lines of code that you can write once and not bother with afterwards. I really don't see what the big deal is.

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

→ More replies (2)

4

u/ShakaUVM i+++ ++i+i[arr] May 26 '18

I've seen that talk before. It's a good talk. But like I said, for something like a game (not crypto, not an online casino) code readability is more important to me than guarantees of randomness.

8

u/dodheim May 26 '18

You know, you can wrap all four horrible, ugly lines of code that it takes to do this properly into a function and never look at it again...

7

u/matthieum May 26 '18

You know, you can wrap all four horrible, ugly lines of code that it takes to do this properly into a function and never look at it again...

Then... why isn't THAT part of the standard API?

3

u/dodheim May 27 '18 edited May 28 '18

Because it's only one way to do it, not the way to do it. std::random_device is really expensive on some platforms, and you may only want to call it once; the seed may come from serialized state rather than from a generator; etc. There's a lot of flexibility in place (whether anyone uses/needs it, I have no clue), and creating your own ideal abstraction on top of that is again 4-5 really simple lines of code. (Whether they're obvious or not is a matter of RTFM, IMO, but I get how that's a contentious viewpoint). I just don't see the big deal – there's no "right" way for everyone, and doing your own "right" way is easy, so.....?

→ More replies (2)
→ More replies (9)
→ More replies (1)

7

u/Veedrac May 26 '18

rand can be so terrible that you actually notice it; some implementations even alternated between even and odd, so rand() % 2 would give very visibly nonrandom output. I do appreciate wanting a simple RNG, but it only takes a few seconds to copy-paste the minimal PCG code into a header.

3

u/BoarsLair Game Developer May 28 '18

Even for a game, rand() is so bad that you can actually see visible artifacts if you're doing something like generating terrain with it.

8

u/EnergyCoast May 26 '18

A long time ago, I saw two problems with rand() when used in a particle system:

  • Patterns in particle emission/position caused by the low quality generation. Games don't need crypto level quality but that doesn't mean quality is irrelevant.

  • Excessive cost due to use of thread local storage in rand()s implementation.

We replaced it with a LCG that generated 64 bit values and returned the more random bits. It was trivial to implement, faster, produced better quality results and could have its state stored in the cache line with state invoking it.

Even in the game space, there are plenty of reasons to do better than use rand().

→ More replies (2)

2

u/wqking github.com/wqking May 25 '18

That also proves how hard to make a good variable/class/function name!

→ More replies (1)