为什么Math.floor()比Math.round()更受青睐? [JavaScript]

时间:2019-07-24 13:28:56

标签: javascript math range rounding

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

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

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

谢谢!

3 个答案:

答案 0 :(得分:0)

Math.floor(Math.random() * (max - min + 1)) + min

将为您提供[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,因此,如果使用Math.round,则随机数将在[min,max]范围内,而不是[min,max + 1]。

  

从WIKIPEDIA

间隔 主条目:区间(数学) 括号()和方括号[]都可以表示间隔。符号{\ 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。等等(任意有限的9s),但不包括12.0。在某些欧洲国家/地区,{\ displaystyle [5,12 [} [5,12 []也用于此符号。

答案 1 :(得分:0)

摘要:因为对于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  |

在示例中,您发现03产生Math.random()的范围只有其他范围的一半。

答案 2 :(得分:0)

Math.floor(Math.random())将始终返回0,而Math.round(Math.random())将返回0 or 1,因此对于Math.round(),随机数将遵循非均匀分布。可能无法满足您的需求。