Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between 0, -0 and +0 [duplicate]

Tags:

javascript

I never understood why -0 treated separately than 0.

The interesting fact is that 0 is equal with -0

> 0 === -0
true

Then, the question is: why is -0 treated separately than 0 and +0?

Is there any case when the sign before 0 matters?

In mathematics +0 is a value just a little greater than 0. Also, -0 is a value just a little lower than 0. For example: n / Infinity would return +0 and n / -Infinity -0 (supposing that n is a real number greater than 0). This happens in mathematics.

like image 283
Ionică Bizău Avatar asked May 26 '26 22:05

Ionică Bizău


1 Answers

"Branch Cuts for Complex Elementary Functions or Much Ado About Nothing's Sign Bit " addresses the reasons for signed zeros. That kind of analysis informed IEEE-754 which is the basis for most modern instruction sets and programming languages' floating point number behavior.

In brief, many common numeric functions can be continuous with signed zeroes at places where they cannot be with an unsigned zero leading to fewer NaN values and fewer special cases. Division is one such function.


Then, the question is: why is -0 treated separately than 0 and +0?

Just to be clear, there are only two zero values. -0 and +0. The tokens (0) can be substituted for the tokens (+0) wherever they occur without changing semantics.


The interesting fact is that 0 is equal with -0

0 === -0
true

This behavior is mandated by IEEE-754.

To test whether two numeric values are the "same":

function same(x, y) {
  if (x === y) {
    if (x !== 0) {
      return true;  // Non-zero values.
    } else {
      return (1/x === 1/y);  // Test signed-ness of zeroes.
    }
  } else {
    return x !== x && y !== y;  // Treat NaNs the same
  }
}
like image 96
Mike Samuel Avatar answered May 28 '26 11:05

Mike Samuel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!