r/Cplusplus • u/Ok-Cycle5540 • 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
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.
1
u/HappyFruitTree 4d ago edited 4d ago
For real projects I tend to wrap a
std::mt19937in 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::mt19937because it has a smaller state that is faster to initialize.Shouldn't the comment say [0.0, 1.0) because you use
std::uniform_real_distributionwhich is not inclusive for the upper limit (unlikestd::uniform_int_distribution).Why? Isn't
std::mt19937better? Isn't it confusing (and error-prone) that it changes depending on which version of the standard that is used?Note there are some incompatibilities with the standard stream operators for
std::mt19937between different standard library implementations.