Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite integer in Python

Python 3 has float('inf') and Decimal('Infinity') but no int('inf'). So, why a number representing the infinite set of integers is missing in the language? Is int('inf') unreasonable?

like image 262
Carlo Pires Avatar asked Jul 05 '14 15:07

Carlo Pires


People also ask

What is an infinite integer?

Infinity is that which is boundless, endless, or larger than any natural number.

Is there an infinite integer?

Infinity 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).

What is type of INF in Python?

In Python, the float type (floating point numbers) includes inf , which represents infinity.


2 Answers

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 
like image 132
Neil G Avatar answered Sep 19 '22 23:09

Neil G


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.

like image 37
Søren V. Poulsen Avatar answered Sep 20 '22 23:09

Søren V. Poulsen