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");
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.
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.
double d = 10.0 / 0; which is positive infinity.
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With