Talespin_Kit
Talespin_Kit

Reputation: 21877

Generating uniform distribution using Math.random()

In the MDN Math.random web page the comment for the example function getRandomInt(..) says that Math.round() was not used since it gives non-uniform distribution, which implies using Math.floor(..) will produce uniform distribution.

// Returns a random integer between min (included) and max (excluded)
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

However, the following code shows that the frequency of generating a random number is directly proportional to the value of the number. i.e Higher the value of the number, higher the frequency. This behaviour is same on nodejs and on firefox browser.

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random


// Returns a random integer between min (included) and max (excluded)
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

var data = {};
var a;
var i = 0;
for (i = 0; i < 100000; ++i) {
  a = getRandomInt(1, 50);

  if (typeof data[a] === 'undefined') { // first time initialize
    data[a] = a;
  } else {
    data[a] = data[a] + a;
  }
}

//console.log(data);
document.getElementById("json").innerHTML = JSON.stringify(data, undefined, 2);
<pre id="json"></pre>

So with this property of Math.random() how to generate a uniform distribution.

Upvotes: 1

Views: 12221

Answers (1)

parchment
parchment

Reputation: 4002

You increment your counter using a. The result of the counter would be a*<actual frequency>.

If you increment with 1, you will see that it actually has a uniform distribution.

if (typeof data[a] === 'undefined') { // first time initialize
    data[a] = 1;
} else {
    data[a] = data[a] + 1;
}

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random


// Returns a random integer between min (included) and max (excluded)
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

var data = {};
var a;
var i = 0;
for (i = 0; i < 100000; ++i)
{
    a = getRandomInt(1,50);

    if (typeof data[a] === 'undefined') { // first time initialize
    data[a] = 1;
    } else {
    data[a] = data[a] + 1;
    }
}
//console.log(data);
document.getElementById("json").innerHTML = JSON.stringify(data, undefined, 2);
<pre id="json"></pre>

Upvotes: 5

Related Questions