javascript - 为什么 Math.floor() 优于 Math.round()? [JavaScript]

标签 javascript math range rounding

我在 FreeCodeCamp 中发现,要解决获取某个范围内的随机整数的问题,可以使用 Math.floor。四舍五入不准确。它返回等于或小于。不是我想的那样。

这是给定的公式: Math.floor(Math.random() * (max - min + 1)) + min

有谁知道为什么它更多地用于四舍五入到最接近的整数?

提前致谢!

最佳答案

总结:因为使用 Math.round() 时,minmax 中的值代表性不足。

<小时/>

让我们举个例子,比较一下分别使用 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() 生成它们的 03 范围只有其他范围的一半范围在示例中。

添加了一个片段来显示该效果:

// 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/

相关文章:

javascript - 如何强制等待jquery更改的第二个选择

math - 在 Coq 中形式化可计算性理论

ios信标扫描间隔

具有 3 个参数的 Python 的 `range` 函数

SQLite 循环语句?

javascript - 如果选中输入类型复选框,则创建和删除输入类型文本

javascript - Angular 4 设置 ng-valid 来处理无效的电子邮件输入

c - 将变化的数字分配给单个变量

algorithm - 在三角等距网格中,给定点位于哪个三角形中?

Javascript:确认消息后无法删除