I come to cross rand()
in C
and found srand()
could only guarantee the reproducibility of the same machine but not the different platform.
As I already used my srand(926)
and completed a quite time-consuming simulation, I like to find the definition of rand()
. So that, I can get the same result on the different platforms as well.
Could someone point me in a direction to find the definition of srand()
in GCC 9.3.0
?
Thanks
CodePudding user response:
gcc is a compiler and as such won't itself have an implementation. srand
is part of the C standard library (libc), the implementation of which is probably glibc on your system.
The following will use the tip of the master branch for glibc at the time of writing. The version used on your system may be different.
srand
is declared here as a weak symbol. Unless overridden, it'll invoke __srandom_r
here, which is defined here. Both random.c and random_r.c appear to have ample documentation for how things work.
CodePudding user response:
Here is a classic definition you can use for your purpose:
/* QuickC by Charlie Gordon 2014-2022 */
#include <limits.h>
#include <stdlib.h>
/* 7.22.2 Pseudo-random sequence generation functions */
static unsigned long int next = 1;
/* 7.22.2.1 The rand function */
int rand(void) {
next = next * 1103515245 12345;
return (unsigned int)(next / 32768) % (RAND_MAX 1);
}
/* 7.22.2.2 The srand function */
void srand(unsigned int seed) {
next = seed;
}