title: Can `rand()` in c++ be used to generate unbiased bools?
body: <p>I have written the following function</p>
  
  <pre><code>bool random_bool(double probability)
  {
      double p_scaled = probability * (RAND_MAX+1) - rand();
      if ( p_scaled &gt;= 1 ) return true;
      if ( p_scaled &lt;= 0 ) return false;
      return random_bool( p_scaled );
  }
  </code></pre>
  
  <p>Given, that <code>rand()</code> generates a number from uniform distribution on <code>{0,1,...,RAND_MAX-1,RAND_MAX}</code> and numbers from subsequent calls can be treated as independent for all practical purposes except cryptography, this should return <code>true</code> with probability <code>p</code>: two <code>if</code> statements return <code>true</code> with probability slightly below <code>p</code>, and <code>false</code> with the probability slightly above <code>1-p</code>, while the recursive call deals with everything else.</p>
  
  <p>However the following test fails:</p>
  
  <pre><code>long long N = 10000000000; //1e10
  double p = 10000.0 / N;
  int counter = 0;
  for (long long i=0;i&lt;N;i++) if (random_bool(p)) counter++;
  assert(9672 &lt; counter &amp;&amp; counter &lt;= 10330);
  </code></pre>
  
  <p>The assert statement is designed to fail only in 0.1% of cases. However it fails all the time (with <code>counter</code> being between 10600 and 10700).</p>
  
  <p>What's wrong?</p>
  
  <p><strong>P.S.:</strong> I've seen <a href="https://stackoverflow.com/questions/3771551/how-to-generate-a-boolean-with-p-probability-using-c-rand-function">this</a> question, but it doesn't help...</p>