Mozilla Developer Network页面上有一些示例:
/**
* Returns a random number between min (inclusive) and max (exclusive)
*/
function getRandomArbitrary(min, max) {
return Math.random() * (max - min) + min;
}
/**
* Returns a random integer between min (inclusive) and max (inclusive)
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}这是它背后的逻辑。这是一个简单的三条规则:
Math.random()返回 0(包括)和 1(不包括)之间的Number 。所以我们有这样的间隔:
[0 .................................... 1)现在,我们想要一个介于min (包含)和max (独占)之间的数字:
[0 .................................... 1)
[min .................................. max)我们可以使用Math.random来获取 [min,max] 区间内的对应关系。但是,首先我们应该通过从第二个区间减去min来考虑一点问题:
[0 .................................... 1)
[min - min ............................ max - min)这给出了:
[0 .................................... 1)
[0 .................................... max - min)我们现在可以应用Math.random然后计算通讯员。我们选择一个随机数:
Math.random()
|
[0 .................................... 1)
[0 .................................... max - min)
|
x (what we need)所以,为了找到x ,我们会做:
x = Math.random() * (max - min);不要忘记添加min ,以便我们在 [min,max] 间隔中得到一个数字:
x = Math.random() * (max - min) + min;这是 MDN 的第一个功能。第二个,返回min和max之间的整数,包括两者。
现在获得整数,你可以使用round , ceil或floor 。
您可以使用Math.round(Math.random() * (max - min)) + min ,但这会产生非均匀分布。 min和max只有大约一半的滚动机会:
min...min+0.5...min+1...min+1.5 ... max-0.5....max
└───┬───┘└────────┬───────┘└───── ... ─────┘└───┬──┘ ← Math.round()
min min+1 max从区间中排除max ,它的滚动机会比min更小。
使用Math.floor(Math.random() * (max - min +1)) + min您可以获得完美均匀的分布。
min.... min+1... min+2 ... max-1... max.... max+1 (is excluded from interval)
| | | | | |
└───┬───┘└───┬───┘└─── ... ┘└───┬───┘└───┬───┘ ← Math.floor()
min min+1 max-1 max你不能在那个等式中使用ceil()和-1 ,因为max现在滚动的机会略少,但你也可以滚动(不需要的) min-1结果。
var randomnumber = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
从Mozilla开发人员网络文档:
// Returns a random integer between min (include) and max (include)
Math.floor(Math.random() * (max - min + 1)) + min;有用的例子:
// 0 - 10
Math.floor(Math.random() * 11);
// 1 - 10
Math.floor(Math.random() * 10) + 1;
// 5 - 20
Math.floor(Math.random() * 16) + 5;
// -10 - (-2)
Math.floor(Math.random() * 9) - 10;