title: Use rand() to generate uniformly distributed floating point numbers on (a,b), [a,b), (a,b], and [a,b]
body: <p>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. Even the relevant results are pages or blogs that are often flat-out wrong or have discussions where self-appointed experts disagree with each other over some technicality, often with their "answers" seemingly exposing that they do not know about the different types (closed, open, semi-open) of intervals. I'm sick of reading bad information about generating random numbers in C for such a "simple" question.</p>
  
  <p>Please show me how to generate uniformly distributed floating point numbers. Here is my typical way (using "long double" as an example) on (a,b), [a,b), (a,b], and [a,b]:</p>
  
  <pre><code>long double a=VALUE1,b=VALUE2;
  long double x1,x2,x3,x4;
  
  srand((unsigned)time(NULL));
  
  /* x1 will be an element of [a,b] */
  x1=((long double)rand()/RAND_MAX)*(b-a) + a;
  
  /* x2 will be an element of [a,b) */
  x2=((long double)rand()/((long double)RAND_MAX+1))*(b-a) + a;
  
  /* x3 will be an element of (a,b] */
  x3=(((long double)rand()+1)/((long double)RAND_MAX+1))*(b-a) + a;
  
  /* x4 will be an element of (a,b) */    
  x4=(((long double)rand()+1)/((long double)RAND_MAX+2))*(b-a) + a;
  </code></pre>
  
  <p>For the special case of the unit intervals (0,1), [0,1), (0,1], and [0,1]:</p>
  
  <pre><code>long double x1,x2,x3,x4;
  
  srand((unsigned)time(NULL));
  
  /* x1 will be an element of [0,1] */
  x1=((long double)rand()/RAND_MAX);
  
  /* x2 will be an element of [0,1) */
  x2=((long double)rand()/((long double)RAND_MAX+1));
  
  /* x3 will be an element of (0,1] */
  x3=(((long double)rand()+1)/((long double)RAND_MAX+1));
  
  /* x4 will be an element of (0,1) */    
  x4=(((long double)rand()+1)/((long double)RAND_MAX+2));
  </code></pre>
  
  <p>I believe the casts on both RAND_MAX and the return value of rand() are necessary, not only because we want to avoid integer division but because they are ints and otherwise adding one (or two) might overflow them.</p>
  
  <p>I think that versions for "double" and "float" are exactly the same but just replacing the type. Are there any subtleties that arise for the different floating point types?</p>
  
  <p>Do you see any problems with the above implementations? If so, what and how would you fix it?</p>
  
  <p>EDIT: The above implementations pass necessary tests for them to be correct (at least on a 64-bit Intel Core 2 Duo machine running 64-bit Linux): x1 can generate both 0 and 1, x2 can generate 0 but hasn't been seen to generate 1, x3 can generate 1 but hasn't been seen to generate 0, and x4 hasn't been seen to generate either 0 or 1.</p>