How predictable is the result of rand() between individual systems?

I plan to create a challenge which will involve predictable randomness. I understand that for a given system, if srand() is seeded using the same value, rand() will return a predictable sequence of results. However I’m not sure to what extent this sequence is consistent between different systems. Will the result be the same as long as the compiler uses the same implementation? Or will the same program on two different systems yield different results?


A random number generator (RNG) is not much code if you simply want good statistical properties without any cryptographic concerns. Include the code for the RNG in your program. Then it will be the same sequence wherever it's run.

Consider something from the PCG family or Xoshiro. M.E. O'Neill's blog has several posts on small RNGs that pass PractRand and TestU01 statistical tests, like Bob Jenkins's Small and 64-bit Minimal Standard generators -- these are just a few lines of code! Here's an example :

uint128_t state = 1;   // can be seeded to any odd number

uint64_t next()
{
    state *= 0x0fc94e3bf4e9ab32866458cd56f5e605;
            // Spectral test: M8 = 0.71005, M16 = 0.66094, M24 = 0.61455
    return state >> 64;
}

To answer what you give in your question:

I’m not sure to what extent this sequence is consistent between different systems. Will the result be the same as long as the compiler uses the same implementation? Or will the same program on two different systems yield different results?

The C standard functions rand and srand use an unspecified algorithm. Which algorithm they use is determined not by the "compiler" or by the "system", but by the C standard library (e.g., glibc or msvcrt*.dll), including its version. For example, the same computer (using the same hardware and operating system) can have two programs that use a different implementation of the C standard library (e.g., glibc versions X and Y, or glibc and the imaginary lib_special_c), which could implement rand and srand differently and could thus produce a different sequence of numbers for a given seed. On the other hand, the same program, running on two different computers, could dynamically link to a different C standard library implementation, and thus use a different implementation of rand and srand. Lxer Lx wrote the following in a comment:

The same executable could link to a different shared library [such as the C standard library] even on the same system, or rand() could be overridden on runtime using dynamic linker tricks such as LD_PRELOAD=./my_rand.so ./a.out. So a statically linked executable, which is rare nowadays, is necessary to expect the same sequence [of numbers] on different systems.

However, for a given version of the C standard library, rand requires the implementation to deliver the same sequence of numbers for a given seed.