title: Avoid division by zero in C when taking log with respect to a random number
body: <p>I am currently using C to generate a Gaussian noise. In one step, I need to take the log of a uniformly distributed number <code>u1 = (double) rand() / RAND_MAX</code>. Because <code>u1</code> may be zero, there is a risk in doing <code>log(u1)</code>. So, I need to check. Should I use</p>
  
  <pre><code>do {
      u1 = ((double) rand() / RAND_MAX);
  } while (u1 == 0.);
  </code></pre>
  
  <p>Or, should I use</p>
  
  <pre><code>do {
      u1 = ((double) rand() / RAND_MAX);
  } while (u1 &lt; epsilon);
  </code></pre>
  
  <p>where <code>epsilon</code> is a small number? If the latter is preferred, how should I choose the value of epsilon? (In Fortran there is <code>TINY</code>, but I do not know what to do in C).</p>
  
  <p>Attached is the complete code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #define _USE_MATH_DEFINES
  #include &lt;math.h&gt;
  #include &lt;stdlib.h&gt;
  
  double gaussian_noise(double mean, double std)
  {
      static int have_spare = 0;
      static double u1, u2, z1, z2;
      if(have_spare)
      {
          have_spare = 0;
          z2 = sqrt(-2. * log(u1)) * sin(2. * M_PI * u2);
          return mean + std * z2;
      }
      have_spare = 1;
      do {
      u1 = ((double) rand() / RAND_MAX);
      } while (u1 == 0.);
      u2 = ((double) rand() / RAND_MAX);
      z1 = sqrt(-2. * log(u1)) * cos(2. * M_PI * u2);
      return mean + std * z1;
  }
  
  void main()
  {
      const double mean = 0., std = 1.;
      double noise;
      int i;
      for(i=0; i&lt;100000; i++)
      {
          noise = gaussian_noise(mean, std);
          printf("%lf\t", noise);
      }
  }
  </code></pre>