I want to collect the \"best\" way to generate random numbers on all four types of intervals in one place. I\'m sick of Googling this. Search results turn up a lot of crap.
If you want every double in the range to be possible, with probability proportional to the difference between it and its adjacent double values, then it's actually really hard.
Consider the range [0, 1000]
. There are an absolute bucketload of values in the very tiny first part of the range: a million of them between 0
and 1000000*DBL_MIN
, and DBL_MIN
is about 2 * 10-308. There are more than 2^32
values in the range altogether, so clearly one call to rand()
isn't enough to generate them all. What you'd need to do is generate the mantissa of your double uniformly, and select an exponent with an exponential distribution, and then fudge things a bit to ensure the result is in range.
If you don't require every double in the range to be possible, then the difference between open and closed ranges is fairly irrelevant, because in a "true" continuous uniform random distribution, the probability of any exact value occurring is 0 anyway. So you might as well just generate a number in the open range.
All that said: yes, your proposed implementations generate values that are in the ranges you say, and for the closed and half-closed ranges they generate the end-points with probability 1/(RAND_MAX+1)
or so. That's good enough for many or most practical purposes.
Your fiddling around with +1 and +2 works provided that RAND_MAX+2
is within the range that double
can represent exactly. This is true for IEEE double precision and 32 bit int
, but it's not actually guaranteed by the C standard.
(I'm ignoring your use of long double
because it confuses things a bit. It's guaranteed to be at least as big as double
, but there are common implementations in which it's exactly the same as double
, so the long
doesn't add anything except uncertainty).