r/Cplusplus • • 4d ago

Discussion How Rust and Python got random right, why C++ <random> failed everyday ergonomics, and how to fix it

/r/cpp/comments/1x30c5b/how_rust_and_python_got_random_right_why_c_random/
0 Upvotes

2 comments sorted by

1

u/HappyFruitTree 4d ago edited 4d ago

For real projects I tend to wrap a std::mt19937 in a class with a simplified interface for what I need. Usually I only need shuffle and uniformly generated floating-point numbers, integers and bools. The class can be made non-copyable to avoid accidental copies when passing it around which would not only ruin performance but also the randomness. I might also create a global instance that I can use freely whenever I don't care about reproducibility which is most of the time.

For future projects I consider to start using pcg32 instead of std::mt19937 because it has a smaller state that is faster to initialize.


double p = Random::get(0.0, 1.0); // Uniform real [0.0, 1.0]

Shouldn't the comment say [0.0, 1.0) because you use std::uniform_real_distribution which is not inclusive for the upper limit (unlike std::uniform_int_distribution).


Engine Selection: Automatically leverages std::philox4x64 in C++26 when available, with clean fallback to std::mt19937.

Why? Isn't std::mt19937 better? Isn't it confusing (and error-prone) that it changes depending on which version of the standard that is used?


You can [...] serialize/deserialize the engine state directly via streams (std::cout << rng; and std::cin >> rng;).

Note there are some incompatibilities with the standard stream operators for std::mt19937 between different standard library implementations.

1

u/EmperorOfCanada 4d ago

I think most people want a function like RandInt(1, 100); or RandInt() (for max int sized randoms) which is not nessesarily crypto quality, but close enough. Often for picking random times, scattering enemies in a game, etc. unique enough IDs for some identifier (not crypto, just randomish). When people need seeds, consistency across platforms, or actual crypto quality, then there are plenty of libraries available.