Uno*_*ing 9 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 |
Run Code Online (Sandbox Code Playgroud)
您会看到这一点0,并且产生它们的范围只有示例中其他所有范围3的一半。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 |
Run Code Online (Sandbox Code Playgroud)
// 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, {})
});Run Code Online (Sandbox Code Playgroud)
小智 0
Math.floor(Math.random() * (max - min + 1)) + min
Run Code Online (Sandbox Code Playgroud)
会给你一个 [min, max] 范围内的随机数,因为 Math.random() 给你 [0, 1)。让我们使用 Math.round 而不是 Math.floor,Math.random() 给出 [0, 1),如果将其乘以 10,则会得到 [0, 10)。这是一个浮点数,如果将其向上舍入,您将得到 [0, 10] 作为整数。但是,如果将其向下舍入,您将得到整数 [0, 10)。
在大多数随机函数中,标准是返回 [min, max)。
为了回答你的问题,作者使用 Math.floor ,以便随机数将在 [min, max] 范围内,而不是使用 Math.round 时的 [min, max+1] 范围内。
来自维基百科
区间 主条目:区间(数学) 括号 ( ) 和方括号 [ ] 也可用于表示区间。符号 {\displaystyle [a,c)} [a, c) 用于表示从 a 到 c 的区间,包含 {\displaystyle a} a 但不包括 {\displaystyle c} c。也就是说, {\displaystyle [5,12)} [5, 12) 将是 5 到 12 之间的所有实数的集合,包括 5 但不包括 12。这些数字可以尽可能接近 12,包括 11.999等等(任意有限数量的 9),但不包括 12.0。在一些欧洲国家,也使用符号 {\displaystyle [5,12[} [5,12[]。
| 归档时间: |
|
| 查看次数: |
11285 次 |
| 最近记录: |