How to implement infinity in Java?

2019-01-12 21:13发布

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.

int myInf = infinity; //However it is done
myInf + 5; //returns infinity
myInf*(-1); //returns negative infinity

I have tried using very large numbers, but I want a proper, easy solution.

8条回答
够拽才男人
2楼-- · 2019-01-12 21:57

I'm supposing you're using integer math for a reason. If so, you can get a result that's functionally nearly the same as POSITIVE_INFINITY by using the MAX_VALUE field of the Integer class:

Integer myInf = Integer.MAX_VALUE;

(And for NEGATIVE_INFINITY you could use MIN_VALUE.) There will of course be some functional differences, e.g., when comparing myInf to a value that happens to be MAX_VALUE: clearly this number isn't less than myInf.

There's also a library that actually has fields POSITIVE_INFINITY and NEGATIVE_INFINITY, but they are really just new names for MAX_VALUE and MIN_VALUE.

查看更多
来,给爷笑一个
3楼-- · 2019-01-12 21:58

For the numeric wrapper types.

e.g Double.POSITVE_INFINITY

Hope this might help you.

查看更多
冷血范
4楼-- · 2019-01-12 21:59

I'm not sure that Java has infinity for every numerical type but for some numerical data types the answer is positive:

Float.POSITIVE_INFINITY
Float.NEGATIVE_INFINITY

or

Double.POSITIVE_INFINITY
Double.NEGATIVE_INFINITY

Also you may find useful the following article which represents some mathematical operations involving +/- infinity: Java Floating-Point Number Intricacies.

查看更多
我想做一个坏孩纸
5楼-- · 2019-01-12 22:01

To use Infinity, you can use Double which supports Infinity: -

    System.out.println(Double.POSITIVE_INFINITY);
    System.out.println(Double.POSITIVE_INFINITY * -1);
    System.out.println(Double.NEGATIVE_INFINITY);

    System.out.println(Double.POSITIVE_INFINITY - Double.NEGATIVE_INFINITY);
    System.out.println(Double.POSITIVE_INFINITY - Double.POSITIVE_INFINITY);

OUTPUT: -

Infinity
-Infinity
-Infinity

Infinity 
NaN
查看更多
爷、活的狠高调
6楼-- · 2019-01-12 22:03

Only Double and Float type support POSITIVE_INFINITY constant.

查看更多
Anthone
7楼-- · 2019-01-12 22:11

The Double and Float types have the POSITIVE_INFINITY constant.

查看更多
登录 后发表回答