在 JavaScript 中生成特定范围内的随机整数

新手上路,请多包涵

如何在 JavaScript 中的两个指定变量之间生成随机整数,例如 x = 4y = 8 将输出 4, 5, 6, 7, 8 中的任何一个?

原文由 zacharyliu 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 808
2 个回答

Mozilla 开发者网络 页面上有一些示例:

 /**
 * 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(不包括)之间的 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 的第一个功能。第二个,返回 minmax 之间的整数,包括两者。

现在要获取整数,您可以使用 roundceilfloor

您可以使用 Math.round(Math.random() * (max - min)) + min ,但这会产生非均匀分布。 minmax 都只有大约一半的滚动机会:

 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 结果。

原文由 Ionuț G. Stan 发布,翻译遵循 CC BY-SA 4.0 许可协议

var randomnumber = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;

原文由 Darin Dimitrov 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题