I quite like being able to generate the same set of pseudo-random data repeatedly, especially with tweaking experimental code. Through observation I would say that rand()
seems to give the same sequence of numbers each time*.
Is it guaranteed to do this for repeated executions on the same machine / for different machines / for different architectures?
*For the same seed obviously.
Yes, given the same environment for the program. From the C standard §7.20.2.2/2,
The
srand
function uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls torand
. Ifsrand
is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated. Ifrand
is called before any calls tosrand
have been made, the same sequence shall be generated as whensrand
is first called with a seed value of 1.
Of course, this assumes it is using the same implementation detail (i.e. same machine, same library at the same execution period). The C standard does not mandate a standard random number generating algorithm, thus, if you run the program with a different C standard library, one may get a different random number sequence.
See the question Consistent pseudo-random numbers across platforms if you need a portable and guaranteed random number sequence with a given seed.