先展示一下精度丢失:

下面是模拟精度丢失的核心代码:
// 定义数组长度
private static final int LEN = 64;
public static void paddingString(double n, StringBuilder sb, int len) {
if (len < 0) {
return;
}
if (n > 1) {
n = n - 1;
paddingString(n, sb, len);
} else if (n < 1) {
n *= 2;
}
if (n > 1) {
sb.append(1);
paddingString(n, sb, --len);
return;
} else if (n < 1) {
sb.append(0);
paddingString(n, sb, --len);
return;
} else {
sb.append(1);
return;
}
}
private static byte[] setBitArray(String s) {
byte[] arr = new byte[LEN];
int temp;
for (int i = LEN; i > 0; i--) {
temp = s.charAt(i - 1) - 48;
arr[i - 1] = (byte) temp;
}
return arr;
}
public static double binaryToDouble(byte[] s) {
BigDecimal two = new BigDecimal(2);
BigDecimal bigDecimal = new BigDecimal(0);
BigDecimal temp = BigDecimal.ONE;
BigDecimal temp1;
for (int i = 0; i < s.length; i++) {
temp = temp.divide(two);
if (s[i] > 0) {
int a = s[i];
temp1 = new BigDecimal(a);
bigDecimal = bigDecimal.add(temp.multiply(temp1));
}
}
return bigDecimal.doubleValue();
}
public static String doubleToBinary(double n) {
StringBuilder stringBuffer = new StringBuilder(LEN);
// 填充并得到二进制结果
paddingString(n, stringBuffer, LEN);
int len;
if ((len = stringBuffer.length()) > LEN + 1) {
return stringBuffer.toString().substring(0, LEN + 1);
} else {
return stringBuffer.toString().substring(0, len);
}
}
public static byte[] bytesAdd(byte[] a, byte[] b) {
byte[] arr = new byte[LEN];
for (int i = LEN - 1; i > 0; i--) {
arr[i] = (byte) (arr[i] + a[i] + b[i]);
if (arr[i] > 1) {
arr[i] -= 2;
arr[i - 1] = 1;
}
}
return arr;
}
精度丢失测试案例:
public static void main(String[] args) {
String s = doubleToBinary(.1); // 转成二进制字符串
byte[] bytes = setBitArray(s); // 转成二进制数组 (一)
double d = binaryToDouble(bytes); // 在转double, 反向验证结果的准确性
System.out.println("十进制: " + d);
System.out.println("========下面同理=========");
String s1 = doubleToBinary(.2);
byte[] bytes1 = setBitArray(s1); // (二)
double d1 = binaryToDouble(bytes1);
System.out.println("十进制: " + d1);
byte[] add = bytesAdd(bytes, bytes1); // 二进制数组累加 (三)
System.out.println("result: " + binaryToDouble(add)); // 将数组转换为小数
}

我们可以看到,已经成功模拟出来了,精度丢失。现在我可以明确的给出精度丢失的原因:存放double数字的数组,它的数组长度是有限的(符号位1,指数位11,尾数部分52,float是1,8,23),所以在数字的小数位转二进制时,如果转换后的二进制是个死循环,那么就会把后面的尾数抛弃掉(从这里发生的精度丢失,位于测试代码的 (一)、(二)部分),最终造成转10进制时,出现了精度丢失!
另外关于如果解决精度丢失问题,用java.math包下的BigDecimal类,前端使用decimal.js
编写不易,如果对你有用,就点个赞吧~多谢
本文通过实例演示了Java中double类型出现精度丢失的原因,即由于double类型的二进制表示长度有限,当小数部分转换为无限循环的二进制时,超出长度的部分会被截断,导致精度损失。文章还提供了使用BigDecimal来避免精度丢失的方法。
4694

被折叠的 条评论
为什么被折叠?



