Infinite integer in Python
Solution 1
You are right that an integer infinity is possible, and that none has been added to the Python standard. This is probably because math.inf
supplants it in almost all cases (as Martijn stated in his comment).
In the meantime, I added an implementation of extended integers on PyPI:
In [0]: from numbers import Integral, Real
In [0]: from extended_int import int_inf, ExtendedIntegral, Infinite
In [0]: i = int_inf
In [4]: float(i)
Out[4]: inf
In [5]: print(i)
inf
In [6]: i ** i
Out[6]: inf
In [7]: i
Out[7]: inf
In [9]: isinstance(i, Real)
Out[9]: True
In [10]: isinstance(i, Integral)
Out[10]: False
In [11]: isinstance(i, Infinite)
Out[11]: True
In [12]: isinstance(i, ExtendedIntegral)
Out[12]: True
In [13]: isinstance(2, ExtendedIntegral)
Out[13]: True
In [14]: isinstance(2, Infinite)
Out[14]: False
Solution 2
Taken from here: https://www.gnu.org/software/libc/manual/html_node/Infinity-and-NaN.html
IEEE 754 floating point numbers can represent positive or negative infinity, and NaN (not a number)
That is, the representation of float
and Decimal
can store these special values. However, there is nothing within the basic type int
that can store the same. As you exceed the limit of 2^32 in an unsigned 32-bit int, you simply roll over to 0 again.
If you want, you could create a class containing an integer which could feature the possibility of infinite values.
Solution 3
For python 2. It is sometimes the case that you need a very large integer. For example, I may want to produce a subarray with x[:n] and, I may wish to sometimes set n to a value such that the whole array will be produced. Since you can't use a float for n (python wants an integer), you need a "large integer". A good way of doing this is to use the largest integer available: sys.maxint. Here is an example:
# MAX_SOURCES = sys.maxint # normal setting
MAX_SOURCES = 5 # while testing
# code to use an array ...
... sources[:MAX_SOURCES]
So, while testing, I could use a smaller sources array but use the full array in production.
Related videos on Youtube
Carlo Pires
Computer engineer with interest in c/c++, python and erlang. Although spends most of the day working with javascript and web technologies like CSS3 and HTML5. In his spare time, does some coding in Julia and Rust.
Updated on July 30, 2020Comments
-
Carlo Pires almost 4 years
Python 3 has
float('inf')
andDecimal('Infinity')
but noint('inf')
. So, why a number representing the infinite set of integers is missing in the language? Isint('inf')
unreasonable?-
Martijn Pieters almost 10 yearsThere is no standard that defines integer infinity. The Floating Point standard however, does. Since
anyinteger < float('inf')
is true, we don't exactly need another infinity value. -
Admin almost 10 yearsInfinity is not an integer. It's not a real number either but it comes up more often in the kind of arithmetic that floating point numbers are used for (e.g. involving transcendental and trigonometric functions). In addition, it's good for representing finite, but too large to represent which can't happen with Python 3
int
. -
Carlo Pires almost 10 years@MartijnPieters, while
anyint < float('inf')
is ok,int(float('inf'))
raises an exception. This lead us to deal with this special number in float/decimal -> integer conversions. -
Martijn Pieters almost 10 years@CarloPires: And that is entirely logical, because it is not a number. Instead, a
OverflowError: cannot convert float infinity to integer
is raised. -
dawg almost 10 yearsFor IEEE floats, inf is a defined bit pattern There is not such defined pattern for any int. You could define one for your own use I suppose.
-
Neil G about 8 years@MartijnPieters The floating point standard has nothing to do with this question.
-
Martijn Pieters about 8 years@NeilG: of course it does. The OP cites the existence of
float('inf')
. That is defined by a standard. There is no such definition for aint('inf')
. -
Neil G about 8 years@MartijnPieters Only because Python doesn't have one. It is possible to have a sentinel class for integer infinities.
-
Martijn Pieters about 8 years@NeilG: so what language does?
-
Neil G about 8 years@MartijnPieters None that I know of. However, I think it would still be a good idea if maybe a bit too much work to justify it.
-
Martijn Pieters about 8 years@NeilG: Sounds like a bad idea then; see the Zen of Python: If the implementation is hard to explain, it's a bad idea.; the same applies to ideas; if they are hard to justify, then why introduce the extra complexity at all?
-
Neil G about 8 years@MartijnPieters Yeah on second thought, most use cases are supplanted by
math.inf
. I think that's a better answer to this question. -
Neil G almost 5 yearsI added an implementation of
int_inf
to my answer. -
Superior almost 4 yearsOne use case for int('inf') would be in for range loops,
for i in range(int('inf'))
which would iterate endlessly. This is now done by while loop, but that looks ugly since you have to increment manually. And what if I mess with myi
inside the loop, then I'd have to copy it toi_
or something like that -
ayorgo about 3 yearsSince
int
is unbounded in Python 3int('inf')
would definitely help with typing, especially when Mypy is used. For example: stackoverflow.com/q/54784280/4755520.
-
-
Carlo Pires almost 10 years2**10000 is fine in Python 3. Integer implementation has no limits anymore, but int('inf') special type is missing.
-
Kevin about 9 yearsYou can use
None
for this. Setting one of the endpoints of a slice toNone
is equivalent to omitting it. -
Pedru over 8 yearsKind of dirty IMHO,in addition to this, sys.maxint has been removed in Python3. Like @Kevin said, use None
-
Neil G about 8 yearsDoesn't answer the question.
-
Cerno over 2 yearsI don't get it. Why is your integer inf a Real and not an Integral? Shouldn't it be exactly the other way around? For me, one use case for an inf integer is to avoid warnings in case a function expects an integer but math.inf would pass as float.
-
Neil G over 2 years@Cerno there is no way to make an infinite integer that satisfies an integer type annotation. And all integers (including infinite ones) are instances of
Real
. Your use case would be satisfied by annotating usingExtendedIntegral
. -
Cerno over 2 yearsI understand the limitations you are operating under. However, if I had to choose between using math.inf (which is straightforward about being a Real number) and an implementation where a seemingly Integral number does not pass the Integral check, I would probably choose the former. The optimal solution, a proper integer inf, does not seem to be achievable, which is unfortunate
-
Neil G over 2 years@Cerno I don't know what you mean by "straightforward". You could use infinite integral when you control the interface, you want type annotations to work, and you want strict type annotations. Your idea would force a loose annotation.
-
Cerno over 2 yearsSorry, maybe I picked the wrong word. What I meant is that math.inf is open about being a float and not an int, so the user would expect
isinstance(math.inf, numbers.Real)
to be True andisinstance(math.inf, numbers.Integral)
to be False. However, if I have an instance ofExtendedIntegral
it is natural to expectisinstance(math.inf, numbers.Integral)
to be True andisinstance(math.inf, numbers.Real)
to False, not the other way around. Maybe I am missing something, but what is the benefit of usingint_inf
overmath.inf
? -
Neil G over 2 yearsThere are a number of errors in your comments: Even with integers the user expects
isinstance(x, numbers.Real)
to be true, so this point of your is irrelevant to the discussion. It is not not "natural" to ever assume that an infinite integer can satisfy theIntegral
interface. It is completely incorrect for an instance ofExtendedIntegral
not to satisfynumbers.Real
—have you testedisinstance(1, numbers.Real)
? Perhaps you should read the interfaces since you don't seem to understand their definition. -
Cerno over 2 yearsYou are right, I was misled by the fact that in C++ we are using helper functions that distinguish between integral and floating types. In these cases a
float
is not integral and anint
is not a floating point number. I did not know that in python an integer is bothReal
andIntegral
. Thanks for clearing that up. I still need clarification on the other issue though: Why would anExtendedIntegral
not beIntegral
? I understand how anIntegral
can also be aReal
, but shouldn't an extension of something still be that something? -
Neil G over 2 years@Carno ExtendedIntegral cannot be Integral since it contains elements that are not Integral.
-
Neil G over 2 years@cerno Have you seen the Numeric Tower?
-
Cerno over 2 yearsYes, I think I understood the numeric tower, insofar as an int is also a rational which is also a real, which is also a complex number which is a number. Looking at your source code it seems like you inserted the ExtendedInteger between the Integral and the Real. So if I get this right, your ExtendedInteger is not an Integer subclass, but more of a superclass?
-
Cerno over 2 yearsSo in your hierarchy a regular Integral is also an ExtendedIntegral, but not vice-versa, right? My confusion apparently came from the naming you chose, because my intuition would be that an extension to a thing is that thing and more. Could you give me a little more insight as to what elements ExtendedIntegral has that do not make it Integral? Isn't the whole point of the type to give the Integral type its own infinity? Wouldn't that just be an Integral with something on top? And if so, shouldn't it be below the Integral in the hierarchy? It seems there's still something I don't understand.
-
Neil G over 2 years@cerno Yes, you got it! The name is analogous to the extended reals. The extended integers are the integers plus two elements: positive and negative infinity. You asked: "shouldn't it be below the Integral"--no, it has to be above. Think about what "is a" means in inheritance.
-
Cerno over 2 yearsAh, so mathematically speaking, we are adding stuff as we go up the hierarchy. So from int to rational we add nominator and denominator, to real we add floating point numbers, to complex we add the imaginary component. I think I was confused, because the way the numeric tower is written, my first take was that it adds functionality as it goes down the hierarchy, but that is just specific functions that are relevant for the current level, or defaults for the extra stuff introduced in the higher levels. It's a bit weird the way it's set up but I think I get it now. Thanks for your patience.