Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement infinity in Java?

People also ask

How do you set infinite in Java?

Use Division With Zero to Implement Infinity in Java We can also simply divide a number with zero to implement infinity in Java.

Do we have infinity in Java?

We have in-built constant variables in Java that hold the infinity value. For example, the Double class contains POSITIVE_INFINITY and NEGATIVE_INFINITY constant variables holding the positive and negative infinity of type double as shown below.

How do you find infinity value in Java?

The isInfinite() method of Java Float class returns a Boolean value for the specified float object or for 'v'. This method returns true if the argument passed is infinitely large in magnitude and returns false for finite floating-point arguments.


double supports Infinity

double inf = Double.POSITIVE_INFINITY;
System.out.println(inf + 5);
System.out.println(inf - inf); // same as Double.NaN
System.out.println(inf * -1); // same as Double.NEGATIVE_INFINITY

prints

Infinity
NaN
-Infinity

note: Infinity - Infinity is Not A Number.


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. Also, as noted in the comments below, incrementing positive infinity will wrap you back around to negative numbers (and decrementing negative infinity will wrap you back to positive).

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.


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

The Double and Float types have the POSITIVE_INFINITY constant.