title: How random is JavaScript's Math.random?
body: <p>For 6 years I've had a <a href="http://andrew.hedges.name/experiments/random/" rel="noreferrer">random number generator</a> page on my website. For a long time, it was the first or second result on Google for "random number generator" and has been used to decide dozens, if not hundreds of contests and drawings on discussion forums and blogs (I know because I see the referrers in my web logs and usually go take a look).</p>
  
  <p>Today, someone emailed me to tell me <strong>it may not be as random as I thought.</strong> She tried generating very large random numbers (e.g., between 1 and 10000000000000000000) and found that they were almost always the same number of digits. Indeed, I wrapped the function in a loop so I could generate thousands of numbers and sure enough, for very large numbers, <strong>the variation was only about 2 orders of magnitude.</strong></p>
  
  <p>Why?</p>
  
  <p>Here is the looping version, so you can try it out for yourself:</p>
  
  <p><a href="http://andrew.hedges.name/experiments/random/randomness.html" rel="noreferrer">http://andrew.hedges.name/experiments/random/randomness.html</a></p>
  
  <p>It includes both a straightforward implementation taken from the <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Math/random" rel="noreferrer">Mozilla Developer Network</a> and some code from 1997 that I swiped off a web page that no longer exists (Paul Houle's "Central Randomizer 1.3"). View source to see how each method works.</p>
  
  <p>I've read <a href="https://stackoverflow.com/questions/424292">here</a> and <a href="http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/VERSIONS/JAVASCRIPT/java-script.html" rel="noreferrer">elsewhere</a> about <strong>Mersenne Twister.</strong> What I'm interested in is why there wouldn't be greater variation in the results from JavaScript's built-in <strong>Math.random</strong> function. Thanks!</p>