2

When I divide a positive double by negative zero, the result returns positive infinity.

double d = 10.0 / -0;

But when I divide a negative double by positive zero, the result returns negative infinity.

double d = -10.0 / 0;

Can someone explain this behavior ? Shouldn't the both operations return negative infinity ?

Abascus
  • 127
  • 2
  • 10
  • That's a good catch. I did not check that with 0.0. – Abascus Jun 24 '21 at 14:40
  • I think I know why the code will not throw an ArithmeticException because we are dealing with double data type. I am curious to know as to why we have this weird behavior when dividing with negative zero. – Abascus Jun 24 '21 at 14:43
  • Have you checked the [second answer?](https://stackoverflow.com/questions/14137989/java-division-by-zero-doesnt-throw-an-arithmeticexception-why#answer-14138032) – samabcde Jun 24 '21 at 14:46

1 Answers1

2

As far as I am aware, there isn't actually a negative integer zero in the Java specification due to the two's complement representation used, which is clarified in answer to this question. Therefore -0 as an integer is just an unsigned 0.

If you run this test with floating point numbers, it performs as you expected:

double d = 10.0 / -0.0; // -Infinity

So the issue isn't with your logic, just your test.

Henry Twist
  • 5,666
  • 3
  • 19
  • 44