Jump to content
  • Advertisement
Sign in to follow this  
MSalley

random integers

This topic is 4704 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

Advertisement

int n = rand();

?

Is that what you're referring to?

If so, make sure to set a new seed for the generator when you start the program or you'll always get the same random numbers. the seed usually comes in the form of the time.. either from when the operating system started, or real time of day.

Share this post


Link to post
Share on other sites
You can use the rand function.

common usage:

int RandomNumber;
RandomNumber = rand();


You might wish to "randomize" the randomizer. For this you need to 'seed' the randomizer.

common method:

srand((unsigned)time(NULL));

rand/srand - include stdlib.h
time - include time.h

HTH

Chad

Share this post


Link to post
Share on other sites
The easiest way to do that is to use the modulus operator.

rand()%n gives a random number between 0 and n-1.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Its the "easiest" way, but its not really correct. The problem is it will not provide an equal chance for all numbers (unless "n" is an even multiple of RAND_MAX+1).

Share this post


Link to post
Share on other sites
Quote:
Original post by Anonymous Poster
Its the "easiest" way, but its not really correct. The problem is it will not provide an equal chance for all numbers (unless "n" is an even multiple of RAND_MAX+1).

More important is that many implementations of rand() aren't very good. They favor the high order bits in terms of randomness, but the modulo method uses the low order bits. This is an issue for any value of n.

A better method is
min + (int)(max*rand()/(RAND_MAX+1.0));
Alternatively, you could use a different RNG. boost provides several good ones, including ways of drawing from a range without messing with silly formulas.

CM

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Some relavent links:

http://www.gamedev.net/community/forums/topic.asp?topic_id=157952
http://www.gamedev.net/community/forums/topic.asp?topic_id=219156

There are more, but you'll have to *search* for them ...

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!