Java中提供了三個特殊的浮點數值:正無窮大、負無窮大、非數,用于表示溢出和出錯。
正無窮大:用一個正數除以0將得到一個正無窮大,通過Double或Float的POSITIVE_INFINITY表示。
負無窮大:用一個負數除以0將得到一個負無窮大,通過Double或Float的NEGATIVE_INFINITY表示。
非數:0.0除以0.0或對一個負數開放將得到一個非數,通過Double或Float的NaN表示。
可以點開jdk源碼,看看java都是如何表示的:
/**
* The {@code Double} class wraps a value of the primitive type
* {@code double} in an object. An object of type
* {@code Double} contains a single field whose type is
* {@code double}.
*
*
In addition, this class provides several methods for converting a
* {@code double} to a {@code String} and a
* {@code String} to a {@code double}, as well as other
* constants and methods useful when dealing with a
* {@code double}.
*
* @author Lee Boynton
* @author Arthur van Hoff
* @author Joseph D. Darcy
* @since JDK1.0
*/
public final class Double extends Number implements Comparable {
/**
* A constant holding the positive infinity of type
* {@code double}. It is equal to the value returned by
* {@code Double.longBitsToDouble(0x7ff0000000000000L)}.
*/
public static final double POSITIVE_INFINITY = 1.0 / 0.0;
/**
* A constant holding the negative infinity of type
* {@code double}. It is equal to the value returned by
* {@code Double.longBitsToDouble(0xfff0000000000000L)}.
*/
public static final double NEGATIVE_INFINITY = -1.0 / 0.0;
/**
* A constant holding a Not-a-Number (NaN) value of type
* {@code double}. It is equivalent to the value returned by
* {@code Double.longBitsToDouble(0x7ff8000000000000L)}.
*/
public static final double NaN = 0.0d / 0.0;
...
}
(實際上在字節碼里正無窮和負無窮還有NaN都有一個特定的值用來表示
0x7f800000表示正無窮
0xff800000表示負無窮
在0x7f800001~0x7fffffff 和?0xff80001~0xffffffff兩個的范圍內的值表示NaN.
)
所有的正無窮大的數值都是相等的,所有的負無窮大的數值都是相等;而NaN不與任何數值相等,甚至和NaN都不等。
舉例
public class javaLesson5
{
public static void main(String[] args)
{
float af = 5.2325556f;
//下面將看到af的值已經發生改變,顯示結果為5.2325554.
System.out.println(af);
double a = 0.0;
double c = Double.NEGATIVE_INFINITY;
float d = Float.NEGATIVE_INFINITY;
//將看到float和double的負無窮大是相等的。顯示結果為:true。
System.out.println(c == d);
//0.0除以0.0將出現非數。顯示結果為:NaN。
System.out.println(a / a);
//兩個非數之間是不相等的。顯示結果為:false。
System.out.println(a == Float.NaN);
//所有正無窮大都是相等的。顯示結果為:true。
System.out.println(6.0 / 0 == 555.0/0);
//負數除以0.0將得到負無窮大。顯示結果為:-Infinity
System.out.println(-8 / a);
//下面代碼將拋出除以0的異常。
//System.out.pintln(0 / 0);
}
}
部分內容轉自(http://blog.csdn.net/ml863606/article/details/50853555)