Search code examples
javafloating-pointintegerdivisionpoint

Java double division positiveness


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");

Solution

  • 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