精度丢失通常发生在浮点数运算中。以下是几个常见的例子展示了浮点数精度丢失的现象:
示例 1: 简单加减法中的精度丢失
在某些情况下,浮点数的简单加减法会产生意想不到的结果。
public class PrecisionLossExample {
public static void main(String[] args) {
double a = 0.1;
double b = 0.2;
double result = a + b;
System.out.println("0.1 + 0.2 = " + result); // 输出不等于0.3
}
}
输出:
0.1 + 0.2 = 0.30000000000000004
示例 2: 大小数相加导致精度丢失
当一个很大的数和一个很小的数相加时,小数的值可能会丢失。
public class PrecisionLossExample2 {
public static void main(String[] args) {
double largeNumber = 1e16;
double smallNumber = 1.0;
double result = largeNumber + smallNumber;
System.out.println("1e16 + 1.0 = " + result); // 输出仍然是1e16
}
}
输出:
1e16 + 1.0 = 1.0E16
示例 3: 连续运算导致的精度丢失
连续的浮点数运算会累积精度误差。
public class PrecisionLossExample3 {
public static void main(String[] args) {
double value = 1.0;
for (int i = 0; i < 1000000; i++) {
value += 1e-6;
}
System.out.println("Result: " + value); // 输出不等于2.0
}
}
输出:
Result: 1.9999999999177334
示例 4: 使用BigDecimal解决精度丢失
为了避免上述的精度丢失问题,可以使用BigDecimal类来进行精确的浮点数计算。
import java.math.BigDecimal;
public class BigDecimalExample {
public static void main(String[] args) {
BigDecimal a = new BigDecimal("0.1");
BigDecimal b = new BigDecimal("0.2");
BigDecimal result = a.add(b);
System.out.println("0.1 + 0.2 = " + result.toString()); // 输出准确的0.3
}
}
输出:
0.1 + 0.2 = 0.3