Orion
Orion

Reputation: 1217

Does C's rand() have to be random?

I was trying to get some info on the specification and implementation of rand() in C, and I can't find much information. As a matter of fact, I can't find anything apart from:

Notably, none of these things require randomness. Specifically, I don't see anything that prohibits this implementation:

int randval = 0;

void srand(unsigned int seed) {
    randval = seed;
    return;
}

int rand() {
    return randval++;
}

This seems somewhat unrandom. Is there a bit of standard I'm missing?

(Also, is is bad to seed rand() with time(), then seed ISAAC with rand()?)

Upvotes: 1

Views: 278

Answers (3)

Jean-Baptiste Yunès
Jean-Baptiste Yunès

Reputation: 36401

It has not to be random but pseudo-random (reproducible and deterministic) as stated in POSIX:

The rand() function shall compute a sequence of pseudo-random integers in the range [0, {RAND_MAX}]

This specification says that it is aligned with ISO-C standard.

Your proposition of implementation does not provide a pseudo-random sequence, obviously. A quick definition of pseudo-random generator could be: "a generator that provides uniform distribution", which yours are clearly not providing such. Your values are too trivially correlated to each others.

Upvotes: 0

Jan Hudec
Jan Hudec

Reputation: 76266

Not only it does not have to be random, it must not be random, because it must be completely deterministic:

§7.22.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 to rand. If srand is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated. If rand is called before any calls to srand have been made, the same sequence shall be generated as when srand is first called with a seed value of 1.

If you need true randomness—for any cryptographic purposes you do—use /dev/random on Linux (and most other unices) and CryptGenRandom on Windows.

If you are instead interested in how well the pseudo-random sequence resembles a random one, that is how much it is statistically random, see @Story Teller's answer.

Upvotes: 2

While notes in the C standard are not normative, it does say this:

7.22.2.1 The rand function / note 295

There are no guarantees as to the quality of the random sequence produced and some implementations are known to produce sequences with distressingly non-random low-order bits. Applications with particular requirements should use a generator that is known to be sufficient for their needs.

So you are correct that a completely lazy implementation of the standard library can look like this. It's not bad to seed rand with time, it's as good as any other seed, and provides a certain degree of randomness so long as it's only seeded once. But I won't use rand for any serious application, precisely due to the lack of guarantees.

Upvotes: 1

Related Questions