java怎么表示正无穷大_java中怎样表示一个无穷大? 无穷小?

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)

你可能感兴趣的:(java怎么表示正无穷大)