9

我试过了

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

输出是

true
true

所以这意味着两种数据类型的“无穷大”是一样的吗?

4

4 回答 4

7

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.

于 2012-04-10T05:13:12.733 回答
1

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.

于 2012-04-10T05:13:20.153 回答
1

在 Java 中没有办法与 a 进行比较floatdouble您可能使用的所有操作都doubledouble隐式向上转换float为 adouble

 float f= 
 double d =
 Double.compare(f, d);
 // equivelent to
 Double.compare((double) f, d);
于 2012-04-10T08:19:22.143 回答
1

在 Java 中,您不能直接将 adouble与 a进行比较float。相反,当您尝试执行此操作时,float会自动转换为double第一个。当您将 a 传递float给带有double参数的方法时,也会发生同样的事情。当你Float.POSITIVE_INFINITY(例如)转换为 a时double,你会得到Double.POSITIVE_INFINITY.

因此,您的问题的答案是Double.POSITIVE_INFINITY并且Float.POSITIVE_INFINITY并不完全相同,但它们都表示“一个太大而无法表示的数字”,因此==给您的答案在逻辑上是一致的。

于 2012-04-10T06:35:16.573 回答