To generate a pseudorandom sequence, the generator must be seeded . A seed fully defines the sequence of numbers to be created. In C, you sow srand as you specify. According to the srand(3) man page, without explicit seeding, it is assumed that the generator will use 1 as a seed. This leads to the fact that you always see the same numbers (but remember that the sequence itself is quite random, the quality depends on the generator used, although the sequence is the same).
User mzabsky points out that one way to get a seed that seems random to the user is with time. Another common method (which I just saw that mzabsky also indicates - sorry) is to seed the generator with the contents of the random number generator of the system, which is extracted from the entropy pool fed by things such as mouse movement, disk time intervals, etc. . You cannot extract a lot of randomness from the generator of the system, since it cannot collect enough entropy. But if you simply extract the seed from it, you would randomly choose a sequence of random numbers in your program. Here is an example of how to do this in C on Linux:
unsigned int seed; FILE* urandom = fopen("/dev/urandom", "r"); fread(&seed, sizeof(int), 1, urandom); fclose(urandom); srand(seed);
In response to Conrad Meyer, I thought I would do some more work. I would divide the use of random numbers into three categories:
- . . If you use random numbers to create seemingly random or varied behaviors, such as in a game, you don't need to think too much about the topic or choosing the right seed. Seed over time, and look at another solution if it turns out to be not good enough. Even relatively bad RNGs will look quite random in this scenario.
- Scientific simulations. If you use random numbers for scientific work, such as calculations in Monte Carlo, you need to take care of choosing a good generator. Your seed must be corrected (or modified by the user). You do not want change (in the sense of the above); you need deterministic behavior, but a good coincidence.
- Cryptography. You will be very careful. This is probably beyond the scope of this topic.
gspr
source share