如何在Java中使用BigDecimal存储无限大?

18

我正在编写返回BigDecimal值的方法内部算法,但有时计算结果会是+或-无穷大。而不是程序崩溃,我想捕获异常并将无穷大作为值返回,就像如果该方法返回double一样。

例如Double.POSITIVE_INFINITY;

那么我该如何在BigDecimal中存储无穷大呢?或者还有其他方法吗?

public static BigDecimal myalgorithm(){

//code to store infinity in a BigDecimal
//return the BigDecimal holding infinity 

}

6
BigDecimal无法表示无穷大。 - Oliver Charlesworth
1
在什么情况下计算结果会是正无穷或负无穷?如果除数为零,BigDecimal.divide将抛出一个算术异常。除此之外,你如何计算正无穷或负无穷? - emory
是的,由于算法的特性,有时可能会出现除以零的情况。目前我只是捕获算术异常并返回+或-999。 - user2989759
2个回答

14

BigDecimal 没有无限大的概念。我可以想到三个选项:

  1. The cleanest approach is probably to derive your own MyBigDecimal class, adding an infinity flag telling you if the instance contains infinity, and overriding the methods to which it would be relevant (which would be most of them, I would think), using the base class's version when you're not holding infinity and your own code when you are.

  2. You could use null as a flag value in your code, although that might be a bit of a pain. E.g.:

    if (theBigDecimal == null) {
        // It's infinity, deal with that
    }
    else {
        // It's finite, deal with that
    }
    
  3. If you're already using null for something else, you could have a BigDecimal instance that doesn't actually contain infinity, but which you pretend containts it, and use == to check against it. E.g.:

    // In your class somewhere:
    static final BigDecimal INFINITE_BIG_DECIMAL = new BigDecimal(); // Value doesn't matter
    
    // Then:
    if (theBigDecimal == INFINITE_BIG_DECIMAL) {
        // It's infinity, deal with that
    }
    else {
        // It's finite, deal with that
    }
    

为什么不直接使用Double? - MGorgon
7
@MGorgon:我认为OP使用BigDecimal是有原因的(例如,任意精度)。 - T.J. Crowder
1
@MGorgon:我正在使用这些算法处理非常大的数字,希望能够处理它们并仍然保持精度。 - user2989759
@user2989759:你的代码需要处理无限概念。最干净的方法是从BigDecimal派生并将该概念添加到类中。然后,您可以(例如)拥有一个类范围的MyBigDecimal.Infinity实例,并在(例如)divide方法中使用:if (this.isInfinite) { return MyBigDecimal.Infinity; } 然后 return super.divide(divisor);(对于非无限情况)。 (当然,您可能还想处理除数为无穷大的情况。) - T.J. Crowder
如果你执行(1),你还需要处理NaN的概念,以处理操作数均为无穷大的操作(在这种情况下,除法和减法结果未定义),或在这些情况下抛出错误。 - wakjah
显示剩余2条评论

-1
一种解决问题的方法是,在这种情况下使用一个非常大的数字:
BigDecimal.valueOf(negative ? Double.MIN_VALUE : Double.MAX_VALUE)

由于BigDecimal没有真正的最大或最小值,因此您可以使用double的最大或最小值。

这种方法的重要性在于,它并不能真正解决表示无穷大的问题,但根据用例,它足以解决问题。我曾经在与您提到的相同用例中使用过它。

实际上,当调用intValue时,double基本上会执行相同的操作。在这种情况下,它将只表示最大整数。


1
Double.MIN_VALUE 大于 0 - cdalxndr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接