| 
  • If you are citizen of an European Union member nation, you may not use this service unless you are at least 16 years old.

  • Want to organize your cloud files? Sign up for a free webinar to see how Dokkio (a new product from PBworks) can help you find, organize, and collaborate on your Drive, Gmail, Dropbox, and Slack files: Weds, May 27 at 2PM Eastern / 11AM Pacific
View
 

SeedRand

Page history last edited by Kenneth Finnegan 10 years, 11 months ago

If you've ever used the stdlib.h rand() function, you've probably noticed that every time you run your program, it gives back the same results.  This is because, by default, the standard (pseudo) random number generator is seeded with the number 1.  To have it start anywhere else in the series, call the function srand(unsigned int seed).  For the seed, you can use the current time in seconds.

 

Code:

#include <time.h>

 

// At the beginning of main, or at least before you use rand()

srand(time(NULL));  

 


Extensions:

Note that this seeds the generator from the current second.  This means that if you expect your program to be rerun more than once a second (some kind of batch processor or simulator maybe), this will not be good enough for you.  A possible workaround is to store the seed in a file, which you then increment every time the program is run.

 

When you're using random numbers, be very considerate about what you're using them for, and how random they need to be.  The standard library rand() function may or may not be good enough for what you're using it for (ie gambling, cryptogaphy, etc)


Sources:

 

Comments (0)

You don't have permission to comment on this page.