Double 和 Floate 在源码上很多地方相似,以下的方法和说明对它们两个都是一致的。
Float:
1.NaN(not a number)
表示不是一个数,例如计算0/0或者负数的平方根结果就是NaN。Java所有的浮点数值计算都遵循IEEE 754标准,用于表示溢出和出错情况的三个特殊的浮点数值:正无穷大,负无穷大,NaN。NaN为自己不等于自己的值 即 x != x
2.equals()方法
Float的equals()方法是比较两个Float类型的值的哈希值是否相等。即还是比较值。(基本类型中,值相等则哈希值相等。)
3.naive关键字修饰的方法
说明:native关键字说明其修饰的方法是一个原生态方法(本地方法),方法对应的实现是在用其他语言实现的文件中。
好处:有效的扩充了jvm。 坏处:损失了很多java的好处,并且有一定开销。
为什么要使用:与java环境外和操作系统交互。
3.compareTo()方法
public static int compare(float f1, float f2) { if (f1 < f2) return -1; // Neither val is NaN, thisVal is smaller if (f1 > f2) return 1; // Neither val is NaN, thisVal is larger //这里如果是f1 == f2,是不是由于精度导致误差的问题所以要有下面的比较? // Cannot use floatToRawIntBits because of possibility of NaNs. int thisBits = Float.floatToIntBits(f1);//floatToIntBits()为返回float浮点值的表示的方法。 int anotherBits = Float.floatToIntBits(f2); return (thisBits == anotherBits ? 0 : // Values are equal (thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN) 1)); // (0.0, -0.0) or (NaN, !NaN) }
4.@SuppressWarnings:该批注的作用是给编译器一条指令,告诉它对被批注的代码元素内部的某些警告保持静默。
“unchecked”: 执行了未检查的转换时的警告,例如当使用集合时没有用泛型 (Generics) 来指定集合保存的类型。
Double:
1.toString():Float 和 Double 的toString()方法在 转换时都会用科学记数法来表示转换出来的数字,故如果不想用科学记数法表示,要用对应的fomat转换。
2.关于Double和Float的表示范围:其并非像int一样,以double为例,最高位为符号位,62-52位为指数位,51-0位为尾数,或者称有效数字位。所以它表示出来的数字远超过64位所能表示的范围。它的部分常量定义为:
public static final double MIN_NORMAL = 0x1.0p-1022; // 2.2250738585072014E-308 public static final double MIN_VALUE = 0x0.0000000000001P-1022; // 4.9e-324 public static final int MAX_EXPONENT = 1023;//指数最大值 public static final int MIN_EXPONENT = -1022;//指数最小值
故其常量会有指数位等的最大最小常量值。
参考链接:https://blog.csdn.net/yangfangjit/article/details/72890779
3.equals()方法:有两个特例:①所有NaN看作相等,尽管Double.NaN == Double.NaN 为false。②+0.0 和 - 0.0 不相等,尽管+0.0 = -0.0(Float同理)
4.longBitsToDouble():注意,此方法不能返回与 long 参数具有完全相同位模式的 double NaN。
参考链接:https://book.2cto.com/201309/31432.html
5.compareTo():
public static int compare(double d1, double d2) { if (d1 < d2) return -1; // Neither val is NaN, thisVal is smaller if (d1 > d2) return 1; // Neither val is NaN, thisVal is larger // Cannot use doubleToRawLongBits because of possibility of NaNs. 注意此处 long thisBits = Double.doubleToLongBits(d1); long anotherBits = Double.doubleToLongBits(d2); return (thisBits == anotherBits ? 0 : // Values are equal (thisBits < anotherBits ? -1 : // (-0.0, 0.0) or (!NaN, NaN) 1)); // (0.0, -0.0) or (NaN, !NaN) }
注意只能用doubleToLongBIts()不能用doubleToRawLongBits(),因为doubleToRawLongBits()如果传入的参数为NaN,则出来的值是实际的NaN的值,而不是像doubleToLongBits()一样是一个统一的值。