yroc
yroc

Reputation: 966

Does C always generate the same random sequence?

I ran a program that called rand() four times. I used the modulus operator to limit the range to 1–6. The integers produced were 2, 5, 4, and 2. I reran the program and got the same numbers. Then I created a brand new program that also called rand() four times, and I still got the integer sequence 2, 5, 4, 2. Then I shut the computer down, powered back up, created another new program that called rand() four times, and still got the sequence 2, 5, 4, 2.

I understand the basics that you need to “seed” the RNG using srand(), which starts the sequence at different points, but I'm just curious: forgetting about seeding for a moment, is the sequence generated by rand() installation, compiler, and/or OS dependent? For example, would any of the following result in a different sequence:

Or is it just a matter of all C compilers using the same RNG algorithm and so the pseudorandom sequence (starting from the beginning) will be the same for everyone?

Upvotes: 4

Views: 663

Answers (3)

John Bode
John Bode

Reputation: 123458

forgetting about seeding for a moment, is the sequence generated by rand() installation, compiler, and/or OS dependent?

It depends on the particular library implementation, which may be part of the compiler installation or installed separately. A different library implementation may give a different sequence. I would expect the same library implementation on two different systems to give the same sequence of values, but that's assuming it doesn't use local system information as part the PRNG algorithm.

The only requirement is that the sequence always be the same for the same seed value, and that if rand is called without a preceding call to srand that it behave as though srand had been called with a seed of 1.

Upvotes: 0

Lee Daniel Crocker
Lee Daniel Crocker

Reputation: 13171

When you say "ran the program four times", it sounds like you're only getting one value of rand() for each seed, which will not be a random sequence. To get a random sequence you need to call srand() once and rand() multiple times in the same program run. If you need a random sequence across executions of a program, you'll have to use something like /dev/random.

Upvotes: 0

ouah
ouah

Reputation: 145829

If you don't call srand, C says:

C99, 7.20.2.2p2) "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."

So if your rand function (which is unspecified in the C Standard and let to the implementation) is an algorithmtic PRNG, it is very likely you get the same sequence again and again if you don't call srand.

Upvotes: 6

Related Questions