So the following code makes 0 < r < 1
r = ((double) rand() / (RAND_MAX))
Why does having r = ((double) rand() / (RAND_MAX + 1))
make -1 < r < 0?
Shouldn't adding one to RAND_MAX make 1 < r < 2?
Edit: I was getting a warning: integer overflow in expression
on that line, so that might be the problem. I just did cout << r << endl
and it definitely gives me values between -1 and 0
This is the right way:
or
No, because RAND_MAX is typically expanded to MAX_INT. So adding one (apparently) puts it at MIN_INT (although it should be undefined behavior as I'm told), hence the reversal of sign.
To get what you want you will need to move the +1 outside the computation:
rand() / double(RAND_MAX)
generates a floating-point random number between 0 (inclusive) and 1 (inclusive), but it's not a good way for the following reasons (because RAND_MAX is usually 32767):Due to the above limitations of rand(), a better choice for generation of random numbers between 0 (inclusive) and 1 (exclusive) would be the following snippet (similar to the example at http://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution ):
This is easy to modify to generate random numbers between 1 (inclusive) and 2 (exclusive) by replacing
unif(0, 1)
withunif(1, 2)
.It doesn't. It makes
0 <= r < 1
, but your original is0 <= r <= 1
.Note that this can lead to undefined behavior if
RAND_MAX + 1
overflows.This is entirely implementation specific, but it appears that in the C++ environment you're working in,
RAND_MAX
is equal toINT_MAX
.Because of this,
RAND_MAX + 1
exhibits undefined (overflow) behavior, and becomesINT_MIN
. While your initial statement was dividing (random # between 0 andINT_MAX
)/(INT_MAX
) and generating a value0 <= r < 1
, now it's dividing (random # between 0 andINT_MAX
)/(INT_MIN
), generating a value-1 < r <= 0
In order to generate a random number
1 <= r < 2
, you would wantIn my case (I'm using VS 2017) works fine the following simple code: