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

时间:2014-11-07 06:03:44

标签: 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);

以下jsfiddle具有上述代码http://jsfiddle.net/hd9tt509/

因此,使用Math.random()的这个属性,如何生成均匀分布。

1 个答案:

答案 0 :(得分:1)

您使用a递增计数器。计数器的结果为a*<actual frequency>

如果您使用1增加,您会看到它实际上具有统一分布。

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

http://jsfiddle.net/hd9tt509/1/

相关问题