Jump to content
  • Advertisement

Archived

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

EvilKind

random positive and negative numbers?

This topic is 5151 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 want to generate random positive and negative numbers. How can I do this with the rand() function or any other routine that I may not of heard off? Thank you for your time!

Share this post


Link to post
Share on other sites
Advertisement
Another random number thread, eh? No offense, but we get tons of these...

If you're using rand(), then one of the best ways would be to use functions like this:
int Random(int Min, int Max)
{
return (int)((double)rand() / (double)RAND_MAX * (Max - Min + 1)) + Min;
}
double Random(double Min, double Max)
{
return (double)rand() / ((double)RAND_MAX + 1.0) * (Max - Min) + Min;
}
There's a lot of typecasting and such going on in there, but the basic concept is that you get a random double that is between 0 and 1 (which is why we divide by RAND_MAX), and then multiply it by the size of the range (Max - Min), and then we just add the minimum value, so whatever was 0 becomes Min, and whatever was at the top of the range becomes Max. Handling integers and floating point numbers is just slightly different, which is why I have two functions.

An easier, but less reliable way, is to mod rand() by the range you want, and then add the minimum value you want, like this:
int Random(int Min, int Max)
{
return rand() % (Max - Min + 1) + Min;
}
This, however, can often lead to easily seen patterns, and thus the randomness no longer seems very random.

And finally, you can look into making your own psuedo-random number generator as well. I hear a lot about mersenne twisters. You can research it if you like.

[Edit - And all of these I have shown naturally support negatives.]

[edited by - Agony on April 16, 2004 10:59:04 AM]

Share this post


Link to post
Share on other sites
quote:
Original post by Agony
Another random number thread, eh? No offense, but we get tons of these...


I had a feeling it was a very common question, but couldn''t find what I was looking for.

Thanks for your help

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

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

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!