Differentiating +0 and −0

Differentiating +0 and −0

本文关键字:and Differentiating      更新时间:2023-09-26

尽管+0和- 0是不同的实体,但+0 === -0的计算结果为true。如何求导+0和- 0呢?

有一个hack:

if (1 / myZero > 0) {
   // myZero is +0
} else {
   // myZero is -0
}

我能做得更好吗?

在ECMAScript 6中,Object.is的行为类似于===,除了它区分正负零,Object.is(NaN, NaN)的计算结果为true

Chrome 24支持Object.is

这仍然是一种hack,但是看一下规范表明:

Math.atan2(0, -0) === Math.PI // true
Math.atan2(0,  0) === 0       // true

根据David Flanagan的书,p. 34, 1除以0将得到相应的无穷大,然后可以用于相等性检查:

1 / 0
> Infinity
1 / -0
> -Infinity

这是无穷的相等比较的行为:

Infinity === -Infinity
> false
Infinity === Infinity
> true
-Infinity === Infinity
> false
-Infinity === -Infinity
> true

要检查负零,这里有一个简单的解决方案。

function isNegativeZero(n) {
    n = Number( n );
    return (n === 0) && (1 / n === -Infinity);
}

人们似乎对这方面的实际需求感到困惑:这是我的用例…

我需要一个解决方案来按索引对表中的列进行排序。单击<th>,用[ordinal]升序调用排序器,用-[ordinal]降序调用排序器。第一列的-0表示降序,0表示升序。

所以我需要区分+0-0,并在这里结束。对我有用的解决方案是在@Šime Vidas的评论中,但有点隐藏。

// This comparison works for all negatives including -0
if ( 1 / x > 0 ) { }
1 / -0 > 0  // false
1 / 0 > 0  // true
1 / -99 > 0 // false
1 / 99 > 0 // true
// WRONG: this naive comparison might give unexpected results
if ( x > 0 ) { }
-0 > 0 // true
// Gotcha

返回+0:

-0 + 0

这无助于区分-0和+0,但这有助于确保某些值不是-0。

1 / -0       => -Infinity  
1 / (-0 + 0) => Infinity

Node.js中一个直接的选项是使用Buffer。

var negZero = Buffer('8000000000000000', 'hex')
var buf = Buffer(8);
buf.writeDoubleBE(myZero);
if (buf.equals(negZero)) {
    // myZero is -0
} else {
    // myZero is +0
}

正如Matt Fenwick所暗示的那样,您可以(使用var zero):

if(1/zero===Infinity) {
  // zero is +0
} else {
  // zero is -0
}

使用Math.sign()

console.log(Math.sign( 1 / +0 ));
console.log(Math.sign( 1 / -0 ));