+0和-0是否相同? [英] Are +0 and -0 the same?
问题描述
阅读 ECMAScript 5.1规范, +区分0
和 -0
。
为什么 +0 === -0
评估为 true
?
推荐答案
JavaScript使用 IEEE 754标准来表示数字。来自维基百科:
JavaScript uses IEEE 754 standard to represent numbers. From Wikipedia:
有符号零为零,并带有相关符号。在普通算术中,-0 = + 0 = 0.但是,在计算中,某些数字表示允许存在两个零,通常用 -0(负零)和 +0表示(正零)。这发生在整数的一些有符号数表示中,并且在大多数浮点数表示中。数字0通常编码为+0,但可以用+0或-0表示。
Signed zero is zero with an associated sign. In ordinary arithmetic, −0 = +0 = 0. However, in computing, some number representations allow for the existence of two zeros, often denoted by −0 (negative zero) and +0 (positive zero). This occurs in some signed number representations for integers, and in most floating point number representations. The number 0 is usually encoded as +0, but can be represented by either +0 or −0.
用于浮点运算的IEEE 754标准(目前大多数都使用)支持浮点数的计算机和编程语言需要+0和-0。零可以被认为是扩展实数线的变体,使得1 / -0 =-∞和1 / + 0 = +∞,除以0仅对于±0 /±0和±∞/±∞未定义。
The IEEE 754 standard for floating point arithmetic (presently used by most computers and programming languages that support floating point numbers) requires both +0 and −0. The zeroes can be considered as a variant of the extended real number line such that 1/−0 = −∞ and 1/+0 = +∞, division by zero is only undefined for ±0/±0 and ±∞/±∞.
本文包含有关不同表示形式的更多信息。
The article contains further information about the different representations.
所以从技术上讲,这就是为什么必须区分零。
So this is the reason why, technically, both zeros have to be distinguished.
但是,
+0 === -0
的计算结果为true。为什么是(...)?
However,
+0 === -0
evaluates to true. Why is that (...) ?
此行为在第11.9.6节,严格的等式比较算法(重点部分是我的):
This behaviour is explicitly defined in section 11.9.6, the Strict Equality Comparison Algorithm (emphasis partly mine):
比较
x === y
,其中x
和y
是值,生成 true 或 false 。这样的比较如下:
The comparison
x === y
, wherex
andy
are values, produces true or false. Such a comparison is performed as follows:
(...)
-
如果Type(x)是Number,那么
If Type(x) is Number, then
- 如果x是NaN,则返回false。
- 如果y为NaN,则返回false。
- 如果x与y的数字值相同,则返回true。
- 如果x为+0,y为-0,返回true。
- 如果x为-0且y为+0,则返回true。
- 返回false。
- 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.
(。 ..)
(同样适用于 +0 == -0
顺便说一句。)
(The same holds for +0 == -0
btw.)
从逻辑上讲,处理 +0
和 -0
相同。否则我们必须在我们的代码中考虑到这一点,我个人不想这样做;)
It seems logically to treat +0
and -0
as equal. Otherwise we would have to take this into account in our code and I, personally, don't want to do that ;)
注意:
ES2015引入了一种新的比较方法, Object.is
。 Object.is
明确区分 -0
和 +0
:
ES2015 introduces a new comparison method, Object.is
. Object.is
explicitly distinguishes between -0
and +0
:
Object.is(-0, +0); // false
这篇关于+0和-0是否相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!