使用Math.random()生成均匀分布
Generating uniform distribution using Math.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>
相关文章:
- 如何防止Math.max()返回NaN
- 用javascript创建一个看起来正常分布的模式
- Math.min()和Math.max()之间有什么区别?在Javascript中
- JavaScript Vector2d Math
- Math.exp() for bigInt?
- 如何使一个Math.random数组元素比另一个数组元素更有可能被选中
- 为什么Math.pow(1,无穷大)返回NaN
- 对变量使用math.max并显示相应的变量
- JavaScript basis 是 math.pow 函数中的十进制数
- Javascript Math.floor 函数失误或实现之谜
- Math.random不断返回相同的答案
- 为什么math.bignumber()返回一个对象?以及我如何使用它
- JS:如何在使用 Math.random() 时排除一系列值
- Math.min.apply 返回 0 表示空值
- Javascript;使用math.random函数随机执行一个操作
- 为什么Java和Javascript Math.round(-1.5)到-1
- Performance: toFixed() vs. Math.floor(x * 10000)
- 掷骰子脚本均匀分布吗?(使用 Math.random())
- 使用Math.random()生成均匀分布
- 百分比分布- JavaScript Math.random()