C++ Tutorial - Random Numbers
Bookmark and Share


Randomness and Random number

Dilbert_random.gif

Source: Dilbert


What's randomness?

What's the difference between pseudo random number and real random number?
Here is a site all about RNADOM: http://www.random.org/randomness/.



Random number in C++

Through out this page, we're limited to pseudo-random numbers.

We can generate a pseudo-random number in the range from 0.0 to 32,767 using rand() function from <cstdlib> library. The maximum value is library-dependent, but is guaranteed to be at least 32767 on any standard library implementation. We can check it from RAND_MAX:

cout << "RAND_MAX=" << RAND_MAX << endl;    // RAND_MAX=32767

We can set the range of generated numbers using % (modulus) operator by specifying a maximum value. For instance, to generate a whole number within the range of 1 to 100:

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
	int i = 0;
	while(i++ < 10) {
		int r = (rand() % 100) + 1;
		cout << r << " ";
	}
	return 0;
}

Smaple output:

42 68 35 1 70 25 79 59 63 65

However, the numbers generated by the rand() are not random because it generates the same sequence each time the code executed. So, if we run the code again, we'll get the same sequence repeated as in the previous run.

To make a different sequence of numbers, we should specify a seed as an argument to a srand() function:

srand(98765);

We will get the diffent sequence of numbers by using the srand(), however, the sequence will still be repeated each time the code is executed. To generate a ever changing sequence, we need to feed something other than static integer to the argument of the srand(0 function.

The best solution is to seed the rand(0 function using the current time as the argument to srand(), by calling time() function from the standard C++ library, <ctime>. This returns the time as the type of time_t. Then, for portability, we cast as an integer type:

srand((int) time(0));

The time() function returns the number of seconds since 00:00 hours, Jan 1, 1970 UTC (i.e., the current unix timestamp). This ensures the number generated by rand() will now seems to be truly random unless it is called again within the same second.

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
	srand((int)time(0));
	int i = 0;
	while(i++ < 10) {
		int r = (rand() % 100) + 1;
		cout << r << " ";
	}
	return 0;
}

If we run the code several times, we get different number sequences.

1st run:
8 5 1 35 88 68 20 86 48 29
next run:
13 6 98 29 74 51 14 49 31 99