Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double.POSITIVE_INFINITY == Float.POSITIVE_INFINITY

I tried

System.out.println(Double.isInfinite(Float.POSITIVE_INFINITY))
System.out.println(Double.isInfinite(Float.NEGATIVE_INFINITY));

and the output was

true
true

So this means "Infinity" is the same for both data types?

like image 620
user113454 Avatar asked Apr 10 '12 05:04

user113454


People also ask

What is double Positive_infinity?

public static final double POSITIVE_INFINITY. A constant holding the positive infinity of type double . It is equal to the value returned by Double.

What is double positive infinity in Java?

Positive InfinityThe constant Double. POSITIVE_INFINITY holds the positive infinity value of type double. This value is obtained by dividing 1.0 by 0.0. Its String representation is Infinity.


2 Answers

Yes and no. Yes, because in an abstract sense infinity is infinity (and, as I explain below, for the purposes of most code floats are converted to doubles anyway).

No, however, because at the bit level the two infinities are different. A double is 64 bits in Java, and a float is 32 bits in Java, so trivially they are different at the representation level.

In Java, floating-point numbers (floats and doubles) are represented using IEEE 754 floating-point format, which is the standard pretty much everyone uses nowadays. Each number is represented in binary as a sign bit, plus a certain number of exponent bits, plus a certain number of mantissa (significand) bits. In either a float or a double, positive infinity is represented with a sign bit of 0, exponent bits all 1, and mantissa bits all 0. Negative infinity is represented the same way, except the sign bit is 1. So infinity is represented in two very similar ways, but because of the differing counts of exponent and mantissa bits between floats and doubles, the bit-level patterns are different.

For the purposes of writing code, you can treat them as the same. Whenever you use doubles and floats together, unless you explicitly say otherwise the float will automatically be cast to a double and the expression will result in a double, so a float infinity "acts like" a double infinity for most practical purposes.

like image 196
Adam Mihalcin Avatar answered Oct 06 '22 23:10

Adam Mihalcin


It depends on what you mean by "same". The bit patterns are different because the sign is different, but they're still both infinite.

In addition, the promotion rules for floats will preserve the infinite nature when converting to a double.

like image 38
paxdiablo Avatar answered Oct 07 '22 00:10

paxdiablo