Generating random numbers with rand()
You may have noticed when using the
rand() found in the standard library of C language, you often get unsatisfied by the 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 you’re random number generator proceed, you can modify a variable on which it relies for its calculations. We call it 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, better find another solution.
Better avoid also enable optimizations features in the compiler (option-O1,-O2-O3 etc ...), when using the rdtsc.