算术运算的溢出和范围检查



在实际应用之前,我们如何检查算术运算是否会超过数据类型的上限。

假设java中缩写的上限是32767,我正在乘以328*100,我实际上无法与Short.MAX_VALUE进行比较,因为相乘后答案已经溢出,答案将是-32736,这肯定比Short.MAX_VALUE

举另一个例子,假设我是计算for循环中17^10(17的幂10)的int值。我怎么知道我的答案在哪个阶段被淹没了。

这个Shortint只是一个例子。从更大的角度思考这个问题,对所有数据类型到底能做些什么。

我试着在谷歌上搜索,但没有找到有助于理解这个概念的好链接。

有三种可能的溢出检查方法:

使用较大的类型并向下转换:将输入转换为下一个较大的基元整数类型并以较大的大小执行算术。检查每个中间结果是否存在原始较小类型的溢出;如果范围检查失败,则抛出ArithmeticException。

预检查输入:检查每个算术运算符的输入,以确保不会发生溢出。当执行操作时操作将溢出时,再次抛出ArithmeticException,否则执行操作。

例如:

static void preAddCheck(int left, int right) throws ArithmeticException {
   if (right > 0 ? left > Integer.MAX_VALUE - right : left < Integer.MIN_VALUE - right) {
    throw new ArithmeticException("Integer overflow");
  }
}

BigInteger:将输入转换为BigInteger类型的对象,并使用BigInteger方法执行所有运算。溢出时引发ArithmeticException。

有一个计划在Java 8的Math包中包含这样的方法,但我不知道目前的状态。这里有一些源代码。我不知道这个实现是如何测试的,但这可以给你一些想法。

例如,int乘法是通过使用long:来完成的

public static int multiplyExact(int x, int y) {
    long r = (long)x * (long)y;
    if ((int)r != r) {
        throw new ArithmeticException("long overflow");
    }
    return (int)r;
}

但长乘法使用了一种更复杂的算法:

public static long multiplyExact(long x, long y) {
    long r = x * y;
    long ax = Math.abs(x);
    long ay = Math.abs(y);
    if (((ax | ay) >>> 31 != 0)) {
        // Some bits greater than 2^31 that might cause overflow
        // Check the result using the divide operator
        // and check for the special case of Long.MIN_VALUE * -1
       if (((y != 0) && (r / y != x)) ||
            (x == Long.MIN_VALUE && y == -1)) {
            throw new ArithmeticException("long overflow");
        }
    }
    return r;
}  

我会使用最大可能的类型BigInteger/BigDecimal进行计算。然后,我会根据其大小将值分配给适当的类型。。。有趣的是,有一些有用的方法。。。如果值不能包含在short中,shortValueExtract将抛出ArithmetricException。。

BigDecimal result = BigDecimal.valueOf(328).multiply(
        BigDecimal.valueOf(100));
try {
    short shortResult = result.shortValueExact();
} catch (ArithmeticException e) {
    // overflow
    System.out.println("Overflow!");
}
try {
    int intResult = result.intValueExact();
} catch (ArithmeticException e) {
    // overflow
}

最新更新