Reputation: 1275
I have looked at many places and cannot seem to find the answer. I understand that the probability of rand() / RAND_MAX == 1
is low because rand()
is unlikely to equal RAND_MAX
.
However is it theoretically possible?
I saw someone write, on something similar, that the range is [0, 1)
, however I do not understand why.
Thanks!
Upvotes: 5
Views: 4563
Reputation: 26703
Quoting from here:
http://en.cppreference.com/w/c/numeric/random/rand
Returns a pseudo-random integer value between 0 and RAND_MAX (0 and RAND_MAX included).
Quoting from standard:
http://port70.net/~nsz/c/c11/n1570.html#7.22
(bold by me)
RAND_MAX which expands to an integer constant expression that is the maximum value returned by the rand function
Those quotes show that RAND_MAX
can be returned, but as you say, very unlikely.
For rand() / RAND_MAX
it means that 1 is actually a possible result, though because of integer division, 0 is the only other possible result.
However, if you calculate in floating points, in order to aslo get the values in between, then be careful with the problems described here:
Is floating point math broken?
Upvotes: 4
Reputation: 234725
Bizarrely rand() / RAND_MAX
will only draw 0 or 1 due to the effects of integer division.
Did you mean 1.0 * rand() / RAND_MAX
? That can draw 0 and 1; the reason being that rand()
is allowed to return RAND_MAX
.
That's an unusual way of having things. Normally you don't want to draw 1, so quite often you'll see
rand() / (RAND_MAX + 1.0)
instead. Note that the 1.0
forces the denominator to assume a floating point type, and the numerator will also therefore be promoted. On its own, RAND_MAX + 1
is liable to overflow an integral type, which could have undefined results.
Upvotes: 5