# Rand and srand

• 02-26-2008
JFonseka
Rand and srand
Code:

```srand ( time(NULL) );                      i = rand () % 18;```
I need a random number chosen for every iteration of the while loop

Code:

```while (d != 6) { srand ( time(NULL) );                      i = rand () % 18; d++; }```
But the problem is, this rand and srand does it per second, so unless i put
Code:

`d! = 10000`
, the number is always the same for 1 whole second, how can i get it to choose a random number every millisecond?
• 02-26-2008
zacs7
Seed the random number generator only once! See the FAQ.
• 02-26-2008
srand() should be called once in your entire program (preferable at the start). This seeds the random generator. I don't know that much about how it works, but I do know that the random number returned by rand() are based on the number given to srand(). If you don't seed it, your program will return the same sequence of random numbers each time you run it.
• 02-26-2008
whiteflags
The one thing is that you're only supposed to seed the pseudo-random number generator once before use, that's just something that you're doing wrong. If you keep re-seeding, than that means you're starting the period over, meaning that you will only get a very different number when the time changes significantly enough.

OTOH, if you fix that and then the seed itself (the time) is inappropriate because it's not random enough, you might want to try hashing the time so that you get less of a seed dependant on the clock.

something simple like:

h(k) = k(k + 3) % RAND_MAX

doesn't have to be difficult, but it depends how random you need to be. If you need to be cryptographically random, you'll need to build and use a different generator than rand().
• 02-26-2008
maverix
check out this site for info on random numbers...its from one of the C board members

http://www.eternallyconfuzzled.com/t..._tut_rand.aspx

cheers
maverix
• 02-26-2008
JFonseka
Ah yea, that fixed it, i just moved it before the loop, and it's working now, that 'hashing' citizen talked about looks interesting, thanks for that, will check it out.

Cheers