Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store infinity in a BigDecimal (Java)?

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 

}
like image 362
user2989759 Avatar asked Dec 28 '13 12:12

user2989759


1 Answers

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
    }
    
like image 120
T.J. Crowder Avatar answered Sep 28 '22 05:09

T.J. Crowder