Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
like image 968
Galen BlueTalon Avatar asked Sep 11 '21 04:09

Galen BlueTalon


People also ask

What is double division in Java?

PROGRAM 2 In Java, when you do a division between an integer and a double, the result is a double. So when you do sum/4.0, the result is the double 7.5.

What happens when you divide a double by an int in Java?

When one of the operands to a division is a double and the other is an int, Java implicitly (i.e. behind your back) casts the int operand to a double. Thus, Java performs the real division 7.0 / 3.0.

What is the result when one tries to compile and run the following code double D 10.0 /- 0?

double d = 10.0 / 0; which is positive infinity.


2 Answers

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
like image 96
Ole V.V. Avatar answered Oct 22 '22 22:10

Ole V.V.


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).

like image 32
null_awe Avatar answered Oct 23 '22 00:10

null_awe