Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to seed srand()? [duplicate]

Tags:

c

random

srand

The way I learned was to initially seed the random number generator with srand(time(NULL)) and then use calls to rand() to generate random numbers. The problem with this approach is if I run my program multiple times in the same second, the random numbers generated will always be the same. What is a good way around this?

like image 248
Matt Avatar asked Apr 06 '13 02:04

Matt


People also ask

How do I seed a rand function?

Besides using time, another common way to seed your rand function is to use the process id of your program, since that is guaranteed to be unique. The actual code is platform-dependent, but if you're on Windows, I believe you can use the function GetCurrentProcessId (), as in

What is the best way to randomize srand ()?

Assuming that the randomness of srand () + rand () is enough for your purposes, the trick is in selecting the best seed for srand. time (NULL) is a good starting point, but you'll run into problems if you start more than one instance of the program within the same second.

What is the best way to read a random seed?

Instead just use something like /dev/random or /dev/urandom directly (read in an int directly from it or something like that). The only real benefit of the libc rand is that given a seed, it is predictable which helps with debugging. Show activity on this post.

What does void srand( unsigned seed) do?

void srand ( unsigned seed ): Seeds the pseudo-random number generator used by rand () with the value seed. Note: The pseudo-random number generator should only be seeded once, before any calls to rand (), and the start of the program.


2 Answers

On POSIX systems, use clock_gettime to get the current time in nanoseconds. If you don't need a lot of bits, you can just forget the PRNG and use the low-order bits of the time as your random number directly. :-)

like image 61
R.. GitHub STOP HELPING ICE Avatar answered Oct 20 '22 10:10

R.. GitHub STOP HELPING ICE


int pid ; // get it as per your OS
timeval t;
gettimeofday(&t, NULL);
srand(t.tv_usec * t.tv_sec * pid);

time gives you values based on second. gettimeofday is based on microseconds. So less chance of the same seed happening. Plus you are also using the process id.

like image 20
user93353 Avatar answered Oct 20 '22 12:10

user93353