hichris123
hichris123

Reputation: 10233

Rand() returns negative numbers when min and max are positive

I am using rand() to create random numbers. When I run my code:

int lowest=10000, highest=90000000000;
int range=(highest-lowest)+1;
for (int index=1; index<2; index++){
c = lowest+int(range*rand()/(RAND_MAX + 1.0));

C returns as both positive and negative numbers. Why is this, and how can I fix it?

Upvotes: 1

Views: 1036

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283713

It's because range * rand() overflowed and wrapped around.

This approach can't be "fixed", because you would just get RAND_MAX of the range possible values, leaving big holes that would never be chosen. (Or, if (INT_MAX - INT_MIN + 1) / (RAND_MAX + 1) is smaller than RAND_MAX, that's how many distinct results you can get)

Use the new C++11 random number generators.

If you can't use C++11, then use bitshifting and OR operators to combine multiple rand() results into a single number. If you got a number outside your range, just try again. Any method of mapping one range onto another will break most of the nice properties of the pseudo-random number, like uniform distribution.

Upvotes: 5

Related Questions