How to implement infinity in Java?

后端 未结 10 1277
别跟我提以往
别跟我提以往 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:39

    The Double and Float types have the POSITIVE_INFINITY constant.

    0 讨论(0)
  • 2020-11-28 03:40

    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.

    0 讨论(0)
  • 2020-11-28 03:43

    Since the class Number is not final, here is an idea, that I don't find yet in the other posts. Namely to subclass the class Number.

    This would somehow deliver an object that can be treated as infinity for Integer, Long, Double, Float, BigInteger and BigDecimal.

    Since there are only two values, we could use the singleton pattern:

    public final class Infinity extends Number {
        public final static Infinity POSITIVE = new Infinity(false);
        public final static Infinity NEGATIVE = new Infinity(true);
        private boolean negative;
        private Infinity(boolean n) {
            negative = n;
        }
    }
    

    Somehow I think the remaining methods intValue(), longValue() etc.. should then be overriden to throw an exceptions. So that the infinity value cannot be used without further precautions.

    0 讨论(0)
  • 2020-11-28 03:44

    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.

    0 讨论(0)
提交回复
热议问题