+0和-0是否相同? [英] Are +0 and -0 the same?

查看:1280
本文介绍了+0和-0是否相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读 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, where x and y are values, produces true or false. Such a comparison is performed as follows:

(...)


  • 如果Type(x)是Number,那么

  • If Type(x) is Number, then


  1. 如果x是NaN,则返回false。

  2. 如果y为NaN,则返回false。

  3. 如果x与y的数字值相同,则返回true。

  4. 如果x为+0,y为-0,返回true。

  5. 如果x为-0且y为+0,则返回true。

  6. 返回false。

  1. If x is NaN, return false.
  2. If y is NaN, return false.
  3. If x is the same Number value as y, return true.
  4. If x is +0 and y is −0, return true.
  5. If x is −0 and y is +0, return true.
  6. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆