srand seed consistency between physical machines
I'm not quite sure how to phrase this question, but I couldn't find any others like it.
Say I have this code:
srand(1);
srand(SOME_DEFINED_CONST_INT);
If I run this executable on a number of different p开发者_StackOverflow中文版hysical machines, is the sequence of rand()
guaranteed to be consistent between them? i.e. if I get 1, 4, 6, 3, 4
on one machine, will I always get that same sequence on the others?
If yes, how can that be proven? Is it part of the standard?
If no, is there anything I could do to make it so?
No, the standard guarantees no such thing. However, the logic of generating the random numbers is inside the C standard library. So if you build the application with the same version of the library, the sequence should be the same. The second part of my answer is just a guess, but the standard definitely doesn't give any guarantees.
As Armen said, it's non standard. However, if you look at the man page for srand()
on Linux, you'll see something interesting:
POSIX 1003.1-2003 gives the following example of an implementation of rand() and srand(), possibly useful when one needs the same sequence on two different machines.
static unsigned long next = 1;
/* RAND_MAX assumed to be 32767 */
int myrand(void) {
next = next * 1103515245 + 12345;
return((unsigned)(next/65536) % 32768);
}
void mysrand(unsigned seed) {
next = seed;
}
As Mat said it is always a good idea to implement the random number generator yourself. Preferably in an object oriented manner. As a nice side effect you can get thread safety and possibly speed besides consistency across platforms. Linear congruential generators http://en.wikipedia.org/wiki/Linear_congruential_generator or mersenne twister http://en.wikipedia.org/wiki/Mersenne_twister will get you far.
I'll add that if you are working under Windows, if you take your exe and move between machines, the srand WILL generate the same numbers, because the implementation of the srand is implementor-specific, but you'll always use the runtime of the same implementor (so if you are using the Microsoft C++, you'll use the srand of Microsoft, and MS won't probably change its implementation of srand today or tomorrow). The same for Linux. Your srand will always be the one of glibc. Unless they change it in glibc, the numbers will be the same.
精彩评论