使用 Math.random() 生成均匀分布

Tal*_*Kit 1 javascript random node.js

MDN Math.random网页中,示例函数的注释getRandomInt(..)表示Math.round()未使用该函数,因为它给出了非均匀分布,这意味着使用 Math.floor(..) 将产生均匀分布

// 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;
}
Run Code Online (Sandbox Code Playgroud)

然而,下面的代码表明,生成随机数的频率与该数字的值成正比。即数字的值越高,频率越高。此行为在Nodejs 和 Firefox 浏览器上是相同的。

// 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;
}
Run Code Online (Sandbox Code Playgroud)
// 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);
Run Code Online (Sandbox Code Playgroud)

那么利用 Math.random() 的这个属性如何生成均匀分布。

par*_*ent 5

您可以使用 增加计数器a。计数器的结果将是a*<actual frequency>

如果您增加1,您会发现它实际上具有均匀分布。

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

if (typeof data[a] === 'undefined') { // first time initialize
    data[a] = 1;
} else {
    data[a] = data[a] + 1;
}
Run Code Online (Sandbox Code Playgroud)
// 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);
Run Code Online (Sandbox Code Playgroud)