You are on page 1of 2

Generating Random Numbers

This week we’re going to generate some random numbers. We need the
function

rand()

which returns a random number between 0 and RAND_MAX. The value of


RAND_MAX varies from one version of C to another but it is usually about
32767. The random numbers are generated from a “uniform” distribution.
This means they are equally likely to fall in any part of the range.

We can use rand() to generate a series of random numbers. First we have to


call the function srand() to start the series off. After that every time you
call rand() it returns a different random number. So for example the
following program will generate a series of 10 random numbers.

#include <iostream.h>
#include <stdlib.h>

int main()
{
int i,seed;

cout << “RAND_MAX “ << RAND_MAX << endl;

cout << “enter seed” << endl;


cin >> seed;

srand(seed);

for(i=0; i<10; i++)


{
cout << rand() << endl;
}

return 0;
}

The function srand() is used to start the series of. It takes an argument
known as a “seed” which is an integer. The above program prompts you to
enter the seed at the beginning. If you run the program twice and give it the
same seed each time you will get the same series of random numbers. If you
give it a different seed, you will get a different series.

• Adapt the above program to find the mean of 1000 random numbers. What
value would you expect this to be?
• Run your program several times with different seeds. How does the value
of the mean vary?
• Change the program so that it finds the mean of 10000 numbers. Does the
mean get closer to its expected value?

For fun only

Try modelling Darwinian evolution. Design your own animals and display
them using the graphics functions. The characteristics of your animals (e.g.
the length of their legs, the size of their heads etc. ) should be determined by a
set of “genes”. Let these genes undergo random variation from one generation
to another. By selecting animals with certain characteristics at each
generation you can get them to evolve.

(Inspired by Richard Dawkins’ “Biomorph” program in his book “The Blind


Watchmaker”)

You might also like