小编典典

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

javascript

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


阅读 391

收藏
2020-04-22

共1个答案

小编典典

一些示例:

/**
 * 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()返回Number介于0(含)和1(不含)之间的。所以我们有一个这样的间隔:

[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,包括两者。

现在,用于获取整数,您可以使用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结果。

2020-04-22