5

Why does this java code yield Positive Infinity?

    double d = 10.0 / -0; 

    System.out.println(d);
    if (d == Double.POSITIVE_INFINITY) 
        System.out.println("Positive Infinity");
    else 
        System.out.println("Negative Infinity");
Mark Dickinson
  • 29,088
  • 9
  • 83
  • 120
Galen BlueTalon
  • 173
  • 4
  • 20

3 Answers3

14

While double distinguishes between positive and negative zero, int does not. So when you convert an int with the value 0 to a double, you always get “positive zero”.

-0 is an int, and it has the value 0.

Divide by “negative zero” to obtain negative infinity. To do so, you need to specify the divisor as a double (not an int):

    double d = 10.0 / -0.0;

    System.out.println(d);
    if (d == Double.POSITIVE_INFINITY) {
        System.out.println("Positive Infinity");
    } else {
        System.out.println("Different from Positive Infinity");
    }
    if (d == Double.NEGATIVE_INFINITY) {
        System.out.println("Negative Infinity");
    } else {
        System.out.println("Different from Negative Infinity");
    }

Output:

-Infinity
Different from Positive Infinity
Negative Infinity
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
3

Negative zero is equal to zero. Therefore,

double d = 10.0 / -0;

is equivalent to

double d = 10.0 / 0;

which is positive infinity.

On the other hand, if you instead have:

double d = 10.0 / -0.0;

you will get negative infinity (since now the second value is a double, which differentiates the positive/negative zero).

null_awe
  • 483
  • 6
  • 17
  • Thank you! I was further confused by " double d = 10.0 / -0f;" which yields Negative Infinity. Why does the 0 as a float turn everything negative? – Galen BlueTalon Sep 11 '21 at 04:59
  • Yes, as @Ole V.V. pointed out, double/int does matter. I've edited my answer to answer that question better – null_awe Sep 11 '21 at 05:02
0

This one output is
double d = 10.0 / -0; ===> Positive Infinity

But If you need get Negative Infinity for the output, you can change the code this one.....

double d = 10.0 / -0.0;

Now , you can get "Negative Infinity" for output.

Reason ---> (data types. first you using double/int.... second option is double/double..... )