Public Group

#### Archived

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

# random positive and negative numbers?

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

## 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 on other sites
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 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.

1. 1
Rutin
40
2. 2
3. 3
4. 4
5. 5

• 18
• 19
• 12
• 14
• 9
• ### Forum Statistics

• Total Topics
633362
• Total Posts
3011531
• ### Who's Online (See full list)

There are no registered users currently online

×