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?
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.