Does Java have anything to represent infinity for every numerical data type? How is it implemented such that I can do mathematical operations with it?
E.g.
int myInf = infinity; //However it is done
myInf + 5; //returns infinity
myInf*(-1); //returns negative infinity
I have tried using very large numbers, but I want a proper, easy solution.
double
supports Infinityprints
note:
Infinity - Infinity
is Not A Number.A generic solution is to introduce a new type. It may be more involved, but it has the advantage of working for any type that doesn't define its own infinity.
If
T
is a type for whichlteq
is defined, you can defineInfiniteOr<T>
withlteq
something like this:I'll leave it to you to translate this to exact Java syntax. I hope the ideas are clear; but let me spell them out anyways.
The idea is to create a new type which has all the same values as some already existing type, plus one special value which—as far as you can tell through public methods—acts exactly the way you want infinity to act, e.g. it's greater than anything else. I'm using
null
to represent infinity here, since that seems the most straightforward in Java.If you want to add arithmetic operations, decide what they should do, then implement that. It's probably simplest if you handle the infinite cases first, then reuse the existing operations on finite values of the original type.
There might or might not be a general pattern to whether or not it's beneficial to adopt a convention of handling left-hand-side infinities before right-hand-side infinities or vice versa; I can't tell without trying it out, but for less-than-or-equal (
lteq
) I think it's simpler to look at right-hand-side infinity first. I note thatlteq
is not commutative, butadd
andmul
are; maybe that is relevant.Note: coming up with a good definition of what should happen on infinite values is not always easy. It is for comparison, addition and multiplication, but maybe not subtraction. Also, there is a distinction between infinite cardinal and ordinal numbers which you may want to pay attention to.