Trying to generate random numbers in C, rand() doesn't generate different numbers each time i compile the code, can anyone tell me how to use srand() or tell any other method for generating.
Example: echo $(($RANDOM%10)) #This will display a random integer between 0 and 9. echo $(($RANDOM%11)) #This will display a random integer between 0 and 10.
In the c programming language, there is an inbuilt method to take care of this. srand() and rand() functions are used to generate random numbers.
Description. The C library function int rand(void) returns a pseudo-random number in the range of 0 to RAND_MAX. RAND_MAX is a constant whose default value may vary between implementations but it is granted to be at least 32767.
In order to generate a sequence of pseudorandom numbers, the generator needs to be seeded. The seed fully determines the sequence of numbers that will be produced. In C, you seed with srand
, as you indicate. According to the srand(3)
man page, no explicit seeding implies that the generator will use 1 as a seed. This expains why you always see the same numbers (but do remember that the sequence itself is pretty random, with quality depending on the generator used, even though the sequence is the same each time).
User mzabsky points out that one way to get a seed that feels random to a human user is to seed with time. Another common method (which I just saw that mzabsky also points out - sorry) is to seed the generator with the contents of the system's random number generator, which draws from an entropy pool fed by things such as mouse movement, disk timings etc. You can't draw a lot of randomness from the system generator, as it won't be able to gather enough entropy. But if you just draw a seed from it, you'll have chosen at random a sequence of random numbers in your program. Here's an example of how to do that in C on Linux:
unsigned int seed;
FILE* urandom = fopen("/dev/urandom", "r");
fread(&seed, sizeof(int), 1, urandom);
fclose(urandom);
srand(seed);
In light of Conrad Meyer's answer, I thought I'd elaborate a bit more. I'd divide the use of random numbers into three categories:
This is commonly used solution:
srand ( time(NULL) );
Execution of all C code is deterministic, so you have to bring in something that is different every time you call the srand
. In this case it is time.
Or you can read data from /dev/random
(open it just like any other file).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With