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

Javascript 使用Math.random()生成均匀分布,javascript,node.js,random,Javascript,Node.js,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

在网页中,示例函数
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;
}
// 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);
但是,下面的代码显示生成随机数的频率与该数的值成正比。i、 e数值越高,频率越高。这种行为在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;
}
// 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);
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
//返回最小值(包含)和最大值(排除)之间的随机整数
//使用Math.round()将得到非均匀分布!
函数getRandomInt(最小值、最大值){
返回Math.floor(Math.random()*(max-min))+min;
}
变量数据={};
var a;
var i=0;
对于(i=0;i<100000;++i)
{
a=getRandomInt(1,50);
如果(数据类型[a]=“未定义”){//第一次初始化
数据[a]=a;
}否则{
数据[a]=数据[a]+a;
}
}
控制台日志(数据);
下面的JSFIDLE具有上述代码


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

您可以使用
a
递增计数器。计数器的结果将是
a*

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