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

问题描述 投票:1回答:3

我的目标是在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)不是更好吗?

谢谢你的时间和答案!

javascript random
3个回答
4
投票

这两者之间有一个显着的区别

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

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


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
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.