I have a program that involves generating random numbers. A problem that I've run across is I use time as the seed for srand, and the program loops in less than a second. That means that it'll generate the same number over and over again. I don't want that. As a solution, I've used sleep(1) to have it wait a little, but that takes to long. Solutions?
Sleep(1) does NOT give a second delay. Sleep(1000) does. So, try a larger number with the Sleep command and see if you get the results you're looking for.
¿You are executing you program inside a loop? ¿or you are executing a loop inside you program?
If the second, do as Peter87 says.
If the first, you could pass the seed as a command line argument and just increase it in every iteration.
Or you could use another source of randomness, like /dev/urandom
Thanks to all of you. First, sleep(1) does work, if it helps I'm on a Linux system. Second, calling it srand only once does not work. Third, I'll try a different source of randomness. Forth, I plan to look that up.
Yes it does. You must be calling it repeatedly by mistake.
EDIT:
Sleeping between rand() calls will do absolutely nothing because rand() does not care about the time.
To elaborate further, RNGs are basically math formulas. srand and rand work something like this (although note this example is extremely simplified):
1 2 3 4 5 6 7 8 9 10 11 12 13 14
constint X = /*some carefully chosen prime number*/
constint Y = /*another carefully chosen prime number*/
int state;
void srand(int seed)
{
state = seed;
}
int rand()
{
state = (state * X) + Y;
return state;
}
The idea is you run a formula using the previous output as the new input. If the formula and constants are chosen carefully, the output appears random. Seeding simply gives the RNG a starting point (an initial input).
So yeah -- there's no way time is the culprit here. srand and rand don't even know/care about time. The only way you'd experience what you are is if you are sranding multiple times. So don't do that.