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 there was a way out

 true true 

So, does this mean that "infinity" is the same for both data types?

+8
java floating-point
source share
4 answers

Yes and no. Yes, because in an abstract sense, infinity is infinite (and, as I will explain below, for the purpose of most code floats, anyway).

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

In Java, floating point numbers (floats and doubles) are represented using the IEEE 754 floating point, which is the standard pretty much everyone uses today. Each number is represented in binary form as a sign bit, plus a certain number of exponent bits, plus a certain number of mantissa bits (significant). In float or double, positive infinity is represented by the signed bit 0, exponential bits of just 1 and the mantissa bits of only 0. Negative infinity is represented in the same way, except for signed bit 1. Thus, infinity is represented in two very similar ways, but Due to the different number of bits of the exponent and the mantissa between floats and doublings, bit level patterns are different.

For the purpose of writing code, you can view them as one and the same. Whenever you use doubles and swim together, unless you explicitly specify otherwise, the float will automatically reset to double and the expression will double, so the infinity of the float "acts like" double infinity "for most practical purposes.

+8
source share

It depends on what you mean by "same." Bit patterns are different from each other because the sign is different, but they are still endless.

In addition, the promotion rules for float remain infinite when converted to double.

+1
source share

In Java, you cannot directly compare double to float . Rather, when you try to do this, the float first automatically converted to double . The same subtle thing happens when you pass a float method that takes a double argument. And when you convert Float.POSITIVE_INFINITY (for example) to double , you get Double.POSITIVE_INFINITY .

So the answer to your question is that Double.POSITIVE_INFINITY and Float.POSITIVE_INFINITY not exactly the same, but they both mean “a number that is too large to represent” and therefore the answer that gives == logically consistent .

+1
source share

It is not possible to compare a float with a double in Java as such. All the operations you are likely to use compare double to double after smoothing the float to double

  float f= double d = Double.compare(f, d); // equivelent to Double.compare((double) f, d); 
+1
source share

All Articles