关于Javascript中的±0与±infinity的考究——基于ECMAScript 2015|+0 -0 +inf -inf
本文初稿发于知乎,有所增删改。
输入以下代码,我们会发现他的对应返回值:
1 | console.log(1/0) |
这是为什么呢?
根据:12.6.3.2 Applying the / Operator
Division of a nonzero finite value by a zero results in a signed
infinity. The sign is determined by the rule already stated above.
非零、有限的值除以零会得到一个有符号的infinity。这个符号有上述规则所决定。
那么,什么是上述规则呢?
同一条目中有:
The sign of the result is positive if both operands have the same
sign, negative if the operands have different signs.
如果两个操作数符号,则结果的符号为正;如果两个操作数具有不相同同的符号,则结果为负。
其实这和数学上的除法运算的正负规则是一致的。
那么,什么是有符号的infinity呢?
set of all possible Number values including the special “Not-a-Number”
(NaN) value, positive infinity, and negative infinity
所有的数中有特殊值:NaN,正负无穷(±infinity)
There are two other special values, called positive Infinity and negative Infinity. For brevity, these values are also referred to for expository purposes by the symbols +∞ and −∞, respectively. (Note that these two infinite Number values are produced by the program expressions +Infinity (or simply Infinity) and -Infinity.)
有俩特殊值,叫正无穷与负无穷……也表示为+∞与-∞…
由上,我们知道他定义了±infinity,与其相关操作与运算。并且这与数学上的±∞对等。而数学上我们知道:
x从0的左侧趋近于0,则1/x的极限为负无穷。反而异之
考虑到精度问题,这与上述定义相呼应。
那为什么还会有-0与0相等呢?
从7.2.13 Strict Equality Comparison(严格的相等比较)
我们知道
If Type(x) is Number, then
If x is NaN, return false.
If y is NaN, return false.
If x is the same Number value as y, return true.
If x is +0 and y is −0, return true.
If x is −0 and y is +0, return true.
Return false
. …如果x为+0,y为-0,则返回真(即相等)(反亦然相同)
这是从定义的说明了为什么-0与相等。
那么为什么这里要这样处理呢。
事实上这种标准源自于IEEE 754,其中规定双精浮点数(也就是js中的数字(number类型))的二进制表示中,第一位为符号位。
所以就出现了-0和0。但是数学意义上我们并没有这样的结果,因此只能强行规定他们相等。
flash也是因为IEEE 754这一标准,考虑了数学运算,所以得到了一致的结果。
扩展阅读: