title: Math.random() returns value greater than one?
body: <p>While playing around with random numbers in JavaScript I discovered a surprising bug, presumably in the V8 JavaScript engine in Google Chrome.  Consider:</p>
  
  <pre class="lang-js prettyprint-override"><code>// Generate a random number [1,5].
  var rand5 = function() {
    return parseInt(Math.random() * 5) + 1;
  };
  
  // Return a sample distribution over MAX times.
  var testRand5 = function(dist, max) {
    if (!dist) { dist = {}; }
    if (!max) { max = 5000000; }
    for (var i=0; i&lt;max; i++) {
      var r = rand5();
      dist[r] = (dist[r] || 0) + 1;
    }
    return dist;
  };
  </code></pre>
  
  <p>Now when I run <code>testRand5()</code> I get the following results (of course, differing slightly with each run, you might need to set "max" to a higher value to reveal the bug):</p>
  
  <pre class="lang-js prettyprint-override"><code>var d = testRand5();
  d = {
    1: 1002797,
    2: 998803,
    3: 999541,
    4: 1000851,
    5: 998007,
    10: 1 // XXX: Math.random() returned 4.5?!
  }
  </code></pre>
  
  <p>Interestingly, I see comparable results in node.js, leading me to believe it's not specific to Chrome.  Sometimes there are different or multiple mystery values (7, 9, etc).</p>
  
  <p>Can anyone explain why I might be getting the results I see?  I'm guessing it has something to do with using <code>parseInt</code> (instead of <code>Math.floor()</code>) but I'm still not sure why it could happen.</p>