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
}
BigDecimal
doesn't have the concept of infinity. I can think of three options:
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.
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
}
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
}