Stuart's Useful C/C++ Pages

How do I make sure that my random numbers are different every time?

If you are using the function rand() to generate pseudo random numbers, you will find that every time you run the program you will get the same set of random numbers. This is because the seed used to get the random numbers is the same. To stop this happening you can use current time. This will only produce different results for processes that start in different seconds so you should also use the ID of the process to distinguish these.

Martin Baeker makes a good point about using random numbers. He says:

"It is always wise to print the calculated seed somewhere - in case you suddenly encounter a bug after 20 successful runnings, caused by a particular sequence of random numbers, you will then be able to reproduce and eliminate it - otherwise you may as well have to wait for another eon."
#include <stdlib.h> // need for srand() function
#include <time.h> // need for time() function
#include <unistd.h> // need for getpid() function
#include <iostream> // need for printing to screen

int main {
// set the seed using the current time and the process ID
// this ensures that every instance uses different seeds.
srand(time(NULL) + getpid());
for(int i = 0 ; i < 10 ; i++){
// output normalised random numbers (0 -> 1)
std::cout << ((double)rand()/(double)RAND_MAX) << std::endl;