Java double division positiveness
Asked Answered
T

3

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");
Trilly answered 11/9, 2021 at 4:46 Comment(3)
Because you're dividing by zero.Thanatos
Negative zero? Zero can't be negative.Hazing
@David In math you are correct. In computing not necessarily. Java and many other programming languages recognize -0.0 as a different value from 0.0. which I admit may be confusing.Venable
V
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
Venable answered 11/9, 2021 at 4:58 Comment(0)
A
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).

Aliunde answered 11/9, 2021 at 4:57 Comment(2)
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?Trilly
Yes, as @Ole V.V. pointed out, double/int does matter. I've edited my answer to answer that question betterAliunde
P
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..... )

Peripatetic answered 11/9, 2021 at 5:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.