在特定范围内以 JavaScript 生成随机整数
2022-08-29 21:51:06
如何在JavaScript中的两个指定变量之间生成随机整数,例如 并会输出任何 ?x = 4
y = 8
4, 5, 6, 7, 8
如何在JavaScript中的两个指定变量之间生成随机整数,例如 并会输出任何 ?x = 4
y = 8
4, 5, 6, 7, 8
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).
* The value is no lower than min (or the next integer greater than min
* if min isn't an integer) and no greater than max (or the next integer
* lower than max if max isn't an integer).
* Using Math.round() will give you a non-uniform distribution!
*/
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
这是它背后的逻辑。这是一个简单的三个规则:
Math.random()
返回介于 0(含)和 1(不含)之间的 a。所以我们有一个这样的间隔:Number
[0 .................................... 1)
现在,我们想要一个介于(包括)和(不包括)之间的数字:min
max
[0 .................................... 1)
[min .................................. max)
我们可以使用 在 [最小,最大] 间隔内获取对应项。但是,首先,我们应该通过从第二个区间中减去来稍微考虑问题:Math.random
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
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;