Python Infinity

It may seem funny, but infinity is a concept that refers to an ambiguous number that can have either a negative or a positive value. Every arithmetic operation, like subtraction, division, or any other-is conducted on infinity, or an infinite value always results in an infinite number.

In computer science, infinite values are frequently used to evaluate the efficiency of computation-intensive algorithms and improve their performance.

The idea of expressing the infinite as an integer goes against the very meaning of infinity. Till now, no coding language has yet found a mechanism to express infinity as an integral value. However, as Python is a dynamic programming language, an infinite number can be represented by a floating-point number. We can use the syntax float("inf") as an integer to express it as infinity. The set of Python symbols for infinite is provided below.

Using float('inf')

As infinity can be both positive and negative, they can be represented as a float('inf') and float('-inf'), respectively. The below code shows the implementation of the above-discussed content:

Code

Output:

This is positive infinity: 
inf
This is negative infinity: 
-inf

Using the Math Module of Python

Infinite integers can be represented using Python's math module also. The code below demonstrates how to do it:

Code

Output:

This is positive infinity: 
inf
This is negative infinity: 
-inf

Using the Decimal Module of Python

Infinite float numbers can also be represented using Python's decimal library.

Decimal('Infinity') is employed for positive infinite values, and Decimal('-Infinity') is used for negative infinite values.

Its implementation is shown in the code below:

Code

Output:

This is positive infinity: 
Infinity
This is negative infinity: 
-Infinity

Using the Numpy Library of Python

Infinite values can also be represented using the Numpy module in Python. We can use np.inf and -np.inf, respectively, for positive and negative infinite values. The code below demonstrates how to express an infinite value using the Numpy library:

Code

Output:

This is positive infinity: 
inf
This is negative infinity: 
-inf

How to Check in Python if a Number is Infinite

The math module's isinf() function, which gives a boolean result, can be used to determine whether a value is infinite. The isinf() function is used in the program below:

Code

Output:

inf is infinite:  True
-inf is infinite: True
450 is infinite: False

Comparison of Infinite and Finite Values

It doesn't get any easier than comparing finite and infinite values. Like how negative infinity is lower than negative real numbers and positive infinity is bigger than any natural integer. Consider the following program for a deeper understanding:

Code

Output:

True
False
True
False
True