1

I was wondering if Java's 'Double.POSITIVE_INFINITY' is a true representation of infinity and, if not, will 'i' from this code:

public class Infinity {
private static int i;

public static void main(String[] args) {
    double inf = Double.POSITIVE_INFINITY;
    for (i = 0; i < inf; i++) {
      }
    System.out.println(i);
   }
}

Ever be printed?

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • 3
    What do you mean with a "true" representation of infinity? That value is defined as a representation of infinity for the type `double`. But you cannot store infinity in an `int`; there is no value that represents infinity for the type `int`. – Jesper Jun 29 '17 at 13:13
  • related: https://stackoverflow.com/questions/33529676/using-double-positive-infinity-in-for-loop-java?rq=1 – Mark Rotteveel Jun 29 '17 at 13:16

3 Answers3

5

i < inf will always be true; i.e. i will never reach Double.POSITIVE_INFINITY.

That's because int will overflow to a negative once it reaches 2,147,483,647.

Note that even if i was a double type, you still wouldn't attain POSITIVE_INFINITY: that's because after the 53rd power of 2, certain single increments are a no-op.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
1

int has 4 bytes. It ranges from -2,147,483,648 to 2,147,483,647. ( see here for example).

Which is way smaller than Double.POSITIVE_INFINITY. ( see here ).

So your loop simply runs over and over and over ...

And a more "philosophical" bonus answer: why do you need to ask other people?! You learn programming by making experiments. Yourself.

In other words: that inner curious to "try and find out" is what helps you becoming a programmer. Asking for clarification is fine; but asking for explanations without you trying anything is the wrong approach. Doing so slows down your learning!

GhostCat
  • 137,827
  • 25
  • 176
  • 248
1

Even if you change your code to

double inf = Double.POSITIVE_INFINITY;
for (double i = 0.0; i < inf; i++) {
}
System.out.println(i);

The loop will never end, since i can never become larger than Double.MAX_VALUE, and Double.MAX_VALUE is still smaller than Double.POSITIVE_INFINITY.

You can prove it by running this snippet:

if (Double.MAX_VALUE > Double.POSITIVE_INFINITY) {
  System.out.println ("max is larger than infinity");
} else {
  System.out.println ("nope");
}

which will print "nope", since Double.POSITIVE_INFINITY is larger than any possible double value. BTW, the compiler marks the System.out.println ("max is larger than infinity"); statement as dead code.

I guess this means you could say 'Double.POSITIVE_INFINITY' is a true representation of infinity.

BTW, the value of POSITIVE_INFINITY is

public static final double POSITIVE_INFINITY = 1.0 / 0.0;

Therefore, since 1.0/0.0 is actually positive infinity, you can say it's a true representation of infinity.

Eran
  • 387,369
  • 54
  • 702
  • 768