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