• Advertisement

Archived

This topic is now archived and is closed to further replies.

Random numbers

This topic is 5988 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have a program that is supposed to generate a random number each time the spacebar is pressed, but I get the same "random" numbers every time (first time: {1, 4, 7, 9, 3}, next time: {1, 4, 7, 9, 3}, etc.). I''m using the rand()%(highest random number) to get my numbers. I''m pretty sure that you can seed the random number generator to get more "random" numbers, but I forgot how from my high school comp. sci. days. Any help would be greatly appreciated. If you don''t have anything to say, then don''t say it at all.

Share this post


Link to post
Share on other sites
Advertisement
add this to your init code

srand((unsigned)time(NULL));

and make sure you have time.h and math.h included

Share this post


Link to post
Share on other sites
You need to seed the generator each time the program starts with the current time, so that it will be different each time the program runs. If you don''t, the same seed will be used and you''ll get the same results each time, like you are now.

To seed:

srand((unsigned)time(NULL));

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
If you take a big enough sample, you will find that eventually the numbers will repeat them selves. Not the same number over and over gain, just the same pattern. If you rand() in several places in your code, or it gets called a random number of time, it''s not that important since each call to rand() will get a random unknown chunk of the pattern, which will change each time around. And even if you don''t, it''s not usually that important.

There are times when having not-so-random random numbers is useful, like when debugging, or using the random number generator to encrypt data. (if you use it for the last one, keep in mind that different librarys can give different numbers with the same seed!)

Useless information no normal person would want to know.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Also, using the % operator can make your numbers a lot less random.

Do something more like this:

rand()/RAND_MAX * highest_num

Share this post


Link to post
Share on other sites

  • Advertisement