Generating Random Numbers with rand()

September 2016

Generating random values and numbers is an integral part of computer programming. Randomisation of numbers can be created with the help of the C language. In C, there is a library function called rand which can be used for this process. There is, however, a problem. On each run of the program, the numbers that are generated by the rand function are exactly the same, as it is dependent on the initial value called seed.Therefore, it is important to specify the initial value used by rand at the program start up, and this can be done by choosing another function called srand.

Generating random numbers with rand()


You may have noticed when using the rand() function in the standard library of C language, you often get unsatisfactory results - they look the same.

For example, when trying 5 random numbers in a row:

#include <stdlib.h>    
#include <stdio.h>

int main()
{
int i;
for(i=0; i<5; i++)
{
printf("%d\n", rand());
}
return 0;
}


Execute the program and examine the results generated:

41    
18467
6334
26500
19169


The outputs are significantly different from each other. But if you run your program once more, you will have the same set of numbers.

To change the way your random number generator works, you can modify a variable on which it relies for its calculations. It is known as a seed.

This seed will change with the function srand():

srand(value of seed)


It needs a number that varies from time to time and that can not be predicted easily. For example, you can take the number of cycles used by the processor since the start. It can be obtained on x86 processors (Intel, AMD), with the assembly command rdtsc. Writing a rdtsc() function calling this assembly command will definitely make your life easier, the syntax below works with gcc under Linux and can be found it with dev C++ under Windows.


#include <stdlib.h>    
#include <stdio.h>

int rdtsc()
{
__asm__ __volatile__("rdtsc");
}

int main()
{
int i;
for(i=0; i<5; i++)
{
srand(rdtsc());
printf("%d\n", rand());
}
return 0;
}


With this code, you will generate random numbers more effectively.


Note:
But be aware this solution works only on x86 processors. If your program is to be platform independent, it is best find another solution.

You should also avoid enabling the optimizations feature in the compiler (option-O1,-O2-O3 etc.) when using the rdtsc.

Related :

This document entitled « Generating Random Numbers with rand() » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.