我在 FreeCodeCamp 中发现,要解决获取某个范围内的随机整数的问题,可以使用 Math.floor
。四舍五入不准确。它返回等于或小于。不是我想的那样。
这是给定的公式:
Math.floor(Math.random() * (max - min + 1)) + min
有谁知道为什么它更多地用于四舍五入到最接近的整数?
提前致谢!
最佳答案
总结:因为使用 Math.round()
时,min
和 max
中的值代表性不足。
让我们举个例子,比较一下分别使用 Math.floor()
和 Math.random()
时的结果。
为了清楚起见,我添加了我们正在比较的两个公式:
min = 0;
max = 3;
result = Math.round(Math.random() * (max - min)) + min;
result = Math.floor(Math.random() * (max - min + 1)) + min;
| result | Math.round() | Math.floor() |
|:------:|:------------:|:------------:|
| 0 | 0.0 - 0.499 | 0 - 0.999 |
| 1 | 0.5 - 1.499 | 1 - 1.999 |
| 2 | 1.5 - 2.499 | 2 - 2.999 |
| 3 | 2.5 - 2.999 | 3 - 3.999 |
您会发现,使用 Math.random()
生成它们的 0
和 3
范围只有其他范围的一半范围在示例中。
添加了一个片段来显示该效果:
// the same random numbers for all arrays, nonone should say these would have any influence.
const randomNumbers = Array(10000).fill().map(Math.random);
//min <= random <= max
const min = 4, max = 7;
// the +1 is to do `random <= max` otherwise it would produce `random < max`
const floored = randomNumbers.map(random => Math.floor(random * (max - min + 1) + min));
const rounded = randomNumbers.map(random => Math.round(random * (max - min) + min));
//utility to count the number of occurances per value
const count = (acc, nr) => (acc[nr] = (acc[nr] || 0) + 1, acc);
console.log({
"Math.floor()": floored.reduce(count, {}),
"Math.round()": rounded.reduce(count, {})
});
.as-console-wrapper{top:0;max-height:100%!important}
关于javascript - 为什么 Math.floor() 优于 Math.round()? [JavaScript],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57184115/