What is the purpose of having both positive and negative zero (+0, also written as 0, and -0)?

痞子三分冷 提交于 2019-12-12 04:18:44

问题


According to the ECMAScript 6.0 specification:

...there is both a positive zero and a negative zero. For brevity, these values are also referred to for expository purposes by the symbols +0 and -0, respectively. (Note that these two different zero Number values are produced by the program expressions +0 (or simply 0) and -0.)

So, +0 and -0 are different Number values but they are considered equal. I've checked that -0 === +0 equates to true.

I assume this is just an artifact of how numbers are stored in memory and that there is no benefit/purpose/use of these values.

Am I correct?

Also, wikipedia states:

while the two zero representations behave as equal under numeric comparisons, they yield different results in some operations

Are there any such operations in JavaScript?


回答1:


It's a matter of how numbers are stored and represented in the memory, and processed, specially for floating point arithmetic.

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.

More in this previous answer



来源:https://stackoverflow.com/questions/34088742/what-is-the-purpose-of-having-both-positive-and-negative-zero-0-also-written

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!