rand() between 0 and 1

This is entirely implementation specific, but it appears that in the C++ environment you’re working in, RAND_MAX is equal to INT_MAX.

Because of this, RAND_MAX + 1 exhibits undefined (overflow) behavior, and becomes INT_MIN. While your initial statement was dividing (random # between 0 and INT_MAX)/(INT_MAX) and generating a value 0 <= r < 1, now it’s dividing (random # between 0 and INT_MAX)/(INT_MIN), generating a value -1 < r <= 0

In order to generate a random number 1 <= r < 2, you would want

r = ((double) rand() / (RAND_MAX)) + 1

Leave a Comment