Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What decides Nan and Infinity in java division operations

Output of the below code confusing me. Why NaN sometimes and Infinity other times ?

public static void main (String[] args) {

    double a = 0.0;
    double b = 1.0;
    int c = 0; 
    System.out.println(a/0.0);
    System.out.println(a/0);
    System.out.println(b/0.0);
    System.out.println(b/0);
    System.out.println(c/0.0);
    System.out.println(c/0);
}

Outputs is:

NaN
NaN
Infinity
Infinity
NaN
Exception in thread "main" java.lang.ArithmeticException: / by zero

What is the deciding factor here ?

like image 539
Vinod Kunnakkattil Avatar asked Aug 11 '18 15:08

Vinod Kunnakkattil


People also ask

Why does Java return infinity?

POSITIVE_INFINITY is the infinity equivalent in Java and it represents a theoretical highest number. ArithmeticException is only defined for division by 0 for integer type values. If you try to divide a positive or a negative floating point number with 0 then you will get infinity or -infinity respectively.

How do you define infinity in Java?

To implement infinity in Java, we can simply divide the number by zero as shown below in the example.

What data type results the division of two integers in Java?

When dividing two integers, Java uses integer division. In integer division, the result is also an integer.

Which method throws an exception for not a number and infinite input values?

isNaN() method This method returns true if the value represented by this object is NaN; false otherwise.


1 Answers

This is because of The IEEE Standard for Floating-Point Arithmetic (IEEE 754) which is a technical standard for floating-point computation established in 1985 by the Institute of Electrical and Electronics Engineers (IEEE).


The purpose:

The IEEE floating-point standard,.. specifies that every floating point arithmetic operation, including division by zero, has a well-defined result. The standard supports signed zero, as well as infinity and NaN (not a number). There are two zeroes: +0 (positive zero) and −0 (negative zero) and this removes any ambiguity when dividing.


The Rule:

In IEEE 754 arithmetic, a ÷ +0 is positive infinity when a is positive, negative infinity when a is negative, and NaN when a = ±0.


Source

like image 69
Yahya Avatar answered Sep 23 '22 14:09

Yahya