C++ Seeding Surprises (2015)

by vsbuffaloon 6/25/2025, 4:11 PMwith 25 comments

by cjfdon 6/28/2025, 3:22 PM

This talks about 'bad' seeding quite a lot. But it really depends on what you need what is bad and what is good. Sometimes you need to have a reproducible program so you need to write the random number generator yourself and/or otherwise fix the algorithm. Then you can use '5' as the seed. This is quite often good enough for simulations. Sometimes you want to create cryptographic randomness. Then you need to somewhere find some seed of true randomness that is not guessable. In a computer game where the level needs some random elements just seeding the random number generator with the current time might be fine. And so on.

by nynxon 6/28/2025, 2:48 PM

Is it possible to initialize a prng in C++’s std correctly?

by b0a04glon 6/28/2025, 3:58 PM

found one more flakiness over cross platform, when seed mt19937 same way on linux and windows, same compiler, same code... but problem is std::random_device or libc internals differ under the hood. some platforms do random_device as true hardware entropy, others fake it or seed from diff system sources. so seed retrieved isn't stable cross platform. that means mt19937 starts from diff states, causing different random sequences

it's not a bug in mt19937 itself, it's how random_device (or libc randomness) works differently across environments. makes cross platform tests flaky even when logic is rock solid

>>

std::random_device rd; // might differ per platform

std::mt19937 gen(rd()); // seed depends on rd output

std::uniform_int_distribution<> dist(1, 100);

int random_number = dist(gen); // different on linux vs windows tho same code

by atemerevon 6/28/2025, 11:06 PM

If you want reproducibility and statelessness, there's random123 which I highly recommend. Particularly useful for GPU code.

(Not cryptographically secure, but passes all statistical tests you throw at it).

by rramadasson 6/28/2025, 2:48 PM

Relevant: A old Reddit discussion by the same author - https://old.reddit.com/r/cpp/comments/32u4m7/the_behavior_of...