Java 浮点类数字运算

浮点数运算可以直接使用 + 和 - 运算符进行加减操作,但可能会有一定的问题:

  • 精度问题
  • 比较问题
  • 累积误差

一、比较大小

比较问题:由于精度问题,直接比较两个浮点数是否相等可能会出错。

1.1 使用 compareTo() 方法

对于 Double 的包装类,可以使用 compareTo() 方法来比较两个 Double 对象的大小。这个方法同样返回一个整数,表示比较的结果

Double a = 0.1 + 0.2;
Double b = 0.3;

int result = a.compareTo(b);
if (result < 0) {
    
    
    System.out.println("a is less than b");
} else if (result > 0) {
    
    
    System.out.println("a is greater than b");
} else {
    
    
    System.out.println("a is equal to b");
}

1.2 使用容差值(Epsilon)比较

double a = 0.1 + 0.2;
double b = 0.3;
double epsilon = 0.000001; // 容差值

if (Math.abs(a - b) < epsilon) {
    
    
    System.out.println("a and b are approximately equal");
} else if (a < b) {
    
    
    System.out.println("a is less than b");
} else {
    
    
    System.out.println("a is greater than b");
}

1.3 使用 Double.compare()

Double.compare() 方法是一个静态方法,可以用来比较两个 double 值。这个方法会返回一个整数,表示第一个值与第二个值的关系:

  • 如果第一个值小于第二个值,则返回负数。
  • 如果第一个值等于第二个值,则返回零。
  • 如果第一个值大于第二个值,则返回正数。
double a = 0.1 + 0.2;
double b = 0.3;

int result = Double.compare(a, b);
if (result < 0) {
    
    
    System.out.println("a is less than b");
} else if (result > 0) {
    
    
    System.out.println("a is greater than b");
} else {
    
    
    System.out.println("a is equal to b");
}

二、求和运算

精度问题:浮点数在计算机中是以近似值存储的,因此在进行加减运算时可能会出现精度损失。
累积误差:在进行多次浮点数运算时,误差可能会累积,导致结果偏差更大。

2.1 使用 BigDecimal 精确求和

// 创建 BigDecimal 对象
BigDecimal num1 = new BigDecimal("0.1");
BigDecimal num2 = new BigDecimal("0.2");

// 精确求和
BigDecimal sum = num1.add(num2);
sum.doubleValue()

猜你喜欢

转载自blog.csdn.net/code_nn/article/details/143200913