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
My guess is that
RAND_MAX
is equal toINT_MAX
and so you're overflowing it to a negative.Just do this:
Or even better, use C++11's random number generators.