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:
for(i=0; i<5; i++)
Execute the program and examine the results generated:
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.
for(i=0; i<5; i++)
With this code, you will generate random numbers more effectively.
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.
This document, titled « Generating Random Numbers with rand() », is available under the Creative Commons
license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM