How to implement infinity in Java?

后端 未结 10 1329
别跟我提以往
别跟我提以往 2020-11-28 03:02

Does Java have anything to represent infinity for every numerical data type? How is it implemented such that I can do mathematical operations with it?

E.g.



        
10条回答
  •  忘掉有多难
    2020-11-28 03:31

    I'm a beginner in Java... I found another implementation for the infinity in the Java documentation, for the boolean and double types. https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.3

    Positive zero and negative zero compare equal; thus the result of the expression 0.0==-0.0 is true and the result of 0.0>-0.0 is false. But other operations can distinguish positive and negative zero; for example, 1.0/0.0 has the value positive infinity, while the value of 1.0/-0.0 is negative infinity.

    It looks ugly, but it works.

    public class Main {
    
        public static void main(String[] args) {
            System.out.println(1.0/0.0);
            System.out.println(-1.0/0.0);
        }
    
    }
    

提交回复
热议问题