Rand and srand without time

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.
call srand only once at the top of main
¿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
Make sure you only call srand() once, somewhere at the top of main().

If you are doing some kind of number crunching, the built-in RNG is not that good. Google around the "Mersenne Twister" for something (much) better.

Hope this helps.
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.

Second, calling it srand only once does not work.


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
const int X = /*some carefully chosen prime number*/
const int 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.
Last edited on
On *nix, use usleep()
http://www.cplusplus.com/forum/unices/10491/#msg49054

You must be doing something wrong if what you say is true; srand() always works properly.
Topic archived. No new replies allowed.