samuelbrody1249
samuelbrody1249

Reputation: 4767

What is default seed?

When I call the following function:

printf("%d\n", rand())
srand(0);
printf("%d\n", rand());

I consistently get the following output:

1804289383
1804289383

What is this number representing before the srand()? And if the point is to make the srand required. Why isn't it initialized to something like 0 or -1 or whatever?

Upvotes: 0

Views: 1770

Answers (1)

Steve Summit
Steve Summit

Reputation: 47942

The "seed" sets the state of a pseudo-random number generator, albeit in a non-obvious way. But whenever you seed it with the same number, you'll always get the next number back from rand(). For the PRNG implementation in your C library (which appears to be glibc), it looks like a seed of 0 leads to a next random number of 1804289383.

There's nothing magic or meaningful about the number 1804289383, it just happens to be the number that your C library's PRNG kicks out after a seed value of 0.

Its a bit of a puzzle why the previous call to rand() -- the first one in your program -- is also returning that same value 1804289383. That puzzled me quite a bit at first, because on startup th C library rand() is supposed to behave as if it had been seeded with a value of 1. But as it turns out, the explanation is that glibc's PRNG also happens to turn a seed of 1 into a next value of 1804289383.

Thinking about srand() can be confusing. For more explanation, see this answer to this question, and also this older question.

Upvotes: 2

Related Questions