更好的算法在JS中生成随机数

时间:2019-03-14 21:10:38

标签: javascript random

我的目标是在JavaScript中生成1到100之间的随机整数。

我当前正在使用此

const random = Math.ceil(Math.random() * 100)
console.log(random)

但是我看到很多地方都有替代解决方案,

const random = Math.floor(Math.random() * 100 + 1)
console.log(random)

产生相同的结果。

我的问题是:

为什么第二个代码比我的第一个更好(如果有更好的话)?
是执行一项操作而不是两项操作(Math.floor()+1)更好吗?

感谢您的时间和答复!

3 个答案:

答案 0 :(得分:4)

两者之间有一个明显的区别

Math.ceil(Math.random() * 100)
Math.floor(Math.random() * 100 + 1)

第一个在理论上有可能以非常小的概率生成0,第二个则没有。

答案 1 :(得分:2)

两者都产生几乎相同的结果。您可以进行定量测试,并查看得出的数字。

const
    getRandomCeil = () => Math.ceil(Math.random() * 100),       // 0 ... 100 0 is less likely
    getRandomFloor = () => Math.floor(Math.random() * 100 + 1); // 1 ... 100

var i,
    count = { ceil: {}, floor: {} };

for (i = 0; i < 1e7; i++) {
    value = getRandomCeil();
    count.ceil[value] = (count.ceil[value] || 0) + 1;
    value = getRandomFloor();
    count.floor[value] = (count.floor[value] || 0) + 1;
}
console.log(count);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:2)

Math.random产生的数字在[0, 1)范围内,这意味着 0是包含在内的 ,而1不是。看两个极端情况:

// When Math.random() returns 0
Math.ceil(0 * 100)         // returns 0 since ceiling of 0 is 0
Math.floor(0 * 100 + 1)    // returns 1

// When Math.random() returns 0.999999...
Math.ceil(0.999999 * 100)  // returns 100
Math.floor(0.999999 + 1)   // returns 100

ceil变量有可能在随机函数正好返回0时返回0; although the probability is very, very little