What decides Nan and Infinity in java division operations

血红的双手。 提交于 2019-12-07 06:58:04

问题


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 ?


回答1:


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



来源:https://stackoverflow.com/questions/51801054/what-decides-nan-and-infinity-in-java-division-operations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!