Question

I am writing algorithms inside methods that return BigDecimal values but now and again the result calculated will be + or - infinity.
Rather than the program crashing I'd like to catch the exception and return infinity as a value like the way you could if the method was returning a double.

eg Double.POSITIVE_INFINITY;

So how do I store infinity in a BigDecimal? Or is there another way of doing this?

public static BigDecimal myalgorithm(){

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

}
Was it helpful?

Solution

BigDecimal doesn't have the concept of infinity. I can think of three options:

  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
    }
    

OTHER TIPS

An approach to the problem would be, to just use a really large number in this case:

BigDecimal.valueOf(negative ? Double.MIN_VALUE : Double.MAX_VALUE)

As BigDecimal does not have a real maximum or minimum value, you can use the ones of double.

Important with this approach is, that it doesn't really solve the problem of representing infinity, but depending on the usecase it can solve the problem well enough. I used it for the same usecase as you have mentioned above.

Actually double does more or less the same when calling intValue on it. In that case it will just represent the maximum integer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top