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

标签 javascript node.js random

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;
}

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

// 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>

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

最佳答案

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

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

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>

关于javascript - 使用 Math.random() 生成均匀分布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26795084/

相关文章:

javascript - 带有具有特定属性的复选框的切换元素

node.js - Twitter 的 Node 回复脚本实际上并未回复

javascript - 如何获得对 get_metadata 片段请求的响应? (node.js Bittorrent BEP 0009)

c - 如何在C中分割随机数并在不使用数组的情况下获得每个数字的频率计数?

c++ - 有没有办法检查 std::random_device 是否实际上是随机的?

javascript - 识别来自 PageWorker 的请求

javascript - D3 onclick、onmouseover 和 mouseout 行为覆盖

javascript - 访问 Apollo Store 就像我以前使用 Redux Store 一样

node.js - Node.js keycloak 中的策略执行

JavaScript - 如何获得第三个 "sub variable"