浮点运算 NaN Infinaty

JLS 4.2.4 p40

1 gradual underflow:精度不能满足,导致下溢。

2 round toward zero:从浮点强转成整型的时候向零看趋近,找到最接近的整数。

3 0.0/0.0 is Not-a-Number。

4 比较运算符 <.<=,>,>=返回false,只要有一个操作数是NaN。
5 对于== 运算符,只要有一个操作数是NaN,返回false。
6 对于 != 运算符,只要有一个操作数是NaN,返回true。
7 当且仅当x 是NaN的时候,x != x 为 true 
8 如果x或者y是NaN,(x < y) == !(x >= y ) 返回false

 

package arkblue.lang;

public class FloatTest {
	public static void main(String[] args) {
		// An example of overflow:
		double d = 1e308;
		System.out.print("overflow produces infinity: ");
		System.out.println(d + "*10==" + d * 10);

		// An example of gradual underflow:
		d = 1e-305 * Math.PI;
		System.out.print("gradual underflow: " + d + "\n ");
		for (int i = 0; i < 4; i++)
			System.out.print(" " + (d /= 100000));
		System.out.println();

		// An example of NaN:
		System.out.print("0.0/0.0 is Not-a-Number: ");
		d = 0.0 / 0.0;
		System.out.println(d);

		// An example of inexact results and rounding:
		System.out.print("inexact results with float:");
		for (int i = 0; i < 100; i++) {
			float z = 1.0f / i;
			if (z * i != 1.0f)
				System.out.print(" " + i);
		}
		System.out.println();

		// Another example of inexact results and rounding:
		System.out.print("inexact results with double:");
		for (int i = 0; i < 100; i++) {
			double z = 1.0 / i;
			if (z * i != 1.0)
				System.out.print(" " + i);
		}
		System.out.println();

		// An example of cast to integer rounding:
		System.out.print("cast to int rounds toward 0: ");
		d = 12345.6;
		System.out.println((int) d + " " + (int) (-d));

		System.out.println(1.0 / -0); // Infinity
		System.out.println(1.0D / -0); // Infinity
		System.out.println(1.0 / 0); // Infinity
		System.out.println(1.0D / 0); // Infinity

		System.out.println(0.0 / 0); // NaN
		System.out.println((1.0D / 0 * 0) != (0.0D / 0)); // true
		System.out.println((1.0D / 0) != (0.0D / 0)); // true
		System.out.println((1.0D / 0 * 0) == (0.0D / 0)); // false
		System.out.println((1.0D / 0 * 0) > (0.0D / 0)); // false
		System.out.println((1.0D / 0 * 0) >= (0.0D / 0)); // false
		System.out.println((1.0D / 0 * 0) < (0.0D / 0)); // false
		System.out.println((1.0D / 0 * 0) <= (0.0D / 0)); // false

		double x = Double.NaN;
		double y = 0.0;
		System.out.println((x < y) == !(x >= y));
	}
}

 

结果:

 

overflow produces infinity: 1.0E308*10==Infinity
gradual underflow: 3.141592653589793E-305
  3.1415926535898E-310 3.141592653E-315 3.142E-320 0.0
0.0/0.0 is Not-a-Number: NaN
inexact results with float: 0 41 47 55 61 82 83 94 97
inexact results with double: 0 49 98
cast to int rounds toward 0: 12345 -12345
Infinity
Infinity
Infinity
Infinity
NaN
true
true
false
false
false
false
false

 

 

 

你可能感兴趣的:(NAT)