Skip to main content

How To Think Like a Computer Scientist C++ Edition The Pretext Interactive Version

Section 10.14 Random seeds

If you have run the code in this chapter a few times, you might have noticed that you are getting the same “random” values every time. That’s not very random!
One of the properties of pseudorandom number generators is that if they start from the same place they will generate the same sequence of values. The starting place is called a seed; by default, C++ uses the same seed every time you run the program.
While you are debugging, it is often helpful to see the same sequence over and over. That way, when you make a change to the program you can compare the output before and after the change.
If you want to choose a different seed for the random number generator, you can use the srand function from the cstdlib library. It takes a single argument, which is an integer between 0 and RAND_MAX .
For many applications, like games, you want to see a different random sequence every time the program runs. A common way to do that is to use a library function like time from the ctime library to generate something reasonably unpredictable and unrepeatable, like the number of seconds on the system clock.

Note 10.14.1.

If you are trying to work with times, there are better modern libraries for doing so. This sample uses ctime as the syntax to do so is simpler.
Listing 10.14.1. Try this program - it should print a different sequence of numbers each time you run it. If you remove the srand call, it will generate the same sequence each time.

Note 10.14.2.

Notice how srand is used once at the start of the program. You generally only want to seed the number generator one time or you will keep resetting the seed and may generate the same "random" number over and over. If you move srand into the loop, that is what you should see happen.

Checkpoint 10.14.1.

If we wanted to generate a random number between 0 and 12, and we have previously declared int int x = random ();, what should be our next line of code?
  • Calling the random() function with no arguments.
  • This always generates the same set of values, using the default seed in C++.
  • Calling srand() on a integer seed.
  • This always generates the same set of values, using the specified seed.
  • Running the gettimeofday() function, and calling srand() on the result.
  • gettimeofday() will generate something reasonably random, which you can then use as a random seed.
You have attempted 1 of 3 activities on this page.