Python Infinity: How to Represent Using Inf + Examples

by | Python

One interesting aspect of Python is its ability to handle mathematical concepts like infinity.

This is quite helpful in scenarios where developers need to perform calculations that involve extremely large numbers or work with unbounded limits.

You can represent an infinite number in Python by passing the ‘inf’ variable into the float function. You can also represent infinity using built-in variables in Python’s math module and the NumPy module.

Furthermore, by using these capabilities to handle infinity, programmers can represent the concept of an unlimited value.

In turn, this avoids using arbitrarily large numbers that can often lead to errors in your code.

So, let’s take a look at how these capabilities work!

Python Infinity

How to Represent an Infinite Number in Python?

Python is a dynamically typed language, meaning it can handle different types of data.

Although there is no direct way to represent infinity as an integer, you can represent it using floating-point values.

This section covers various ways to represent positive and negative infinity in Python using the float and decimal functions.

We’ll also take a look at how you can achieve the same with the math and NumPy modules.

1. Float(‘inf’)

The float function is the simplest way to represent infinity in Python.

By passing the string ‘inf’ as an argument to the float function, you initialize a positive infinite floating-point number.

Similarly, the string ‘-inf‘ creates a negative infinite floating-point value. Here’s an example:

positive_infinity = float('inf') 
negative_infinity = float('-inf')

print(f'Positive infinity value: {positive_infinity}')
print(f'Negative infinity value: {negative_infinity}')


Positive infinity inf negative infinity -inf

2. Math.inf

The math module is a built-in library that provides mathematical functions in Python. It includes a constant named inf that represents positive infinity.

By using this constant, you can assign variables to positive and negative infinity, like so:

import math

positive_infinity = math.inf #Positive infinity value
negative_infinity = -math.inf #Negative infinity value

3. Numpy.inf

NumPy is a popular library in Python that provides support for working with numerical arrays and matrices. It introduces a constant named inf that signifies positive infinity.

You can utilize this constant to assign variables to positive and negative infinity:

import numpy as np

positive_infinity = np.inf
negative_infinity = -np.inf

4. Decimal(‘infinity’)

The Decimal module provides a means for handling and performing accurate arithmetic operations on floating numbers.

You can use the decimal library to represent infinite numbers by passing the ‘Infinity’ keyword into the decimal function.

For example:

from decimal import Decimal

positive_infinity = Decimal('infinity')
negative_infinity = Decimal('-infinity')



In conclusion, Python offers various ways to represent positive and negative infinity, depending on your requirements and the libraries you use.

Whether using float(‘inf’), Decimal(‘Infinity’), math.inf, or numpy.inf, Python ensures consistent behavior when it comes to arithmetic operations involving infinity.

In the next section, we’ll take a look at how you can perform arithmetic operations using infinite numbers in Python.

Arithmetic Operations with Infinite Numbers in Python

Arithemtic Operations With Infinte numbers

Performing arithmetic operations with infinite values can lead to some interesting results.

In this section, we’ll discuss the outcomes of addition, subtraction, multiplication, and division involving infinite and finite values.

1. Addition

When adding an infinite value and a finite number, the result will always be infinite whether the infinite variable has a negative or positive value.

The same rule applies when adding two infinite values of the same sign. Here are some examples:

import numpy as np

postive inf = Float('inf')
negative_inf = -np.inf

print(positive_inf + 5)
print(negative_inf + 5)
print(positive_inf + positive_inf)
print(positive_inf + negative_inf)



2. Subtraction

Subtracting a finite number from an infinite value will leave the result as infinity. However, subtracting two infinite values of the same sign can lead to an undefined outcome.

Consider the following examples:

from decimal import Decimal
import math

positive_inf = math.inf
negative_inf = -math.inf

print(positive_inf - 5)
print(negative_inf - 5)
print(positive_inf - positive_inf)
print(positive_inf - negative_inf)



Note: nan represents “not a number”, an undefined result in Python.

3. Multiplication

Multiplying an infinite value by a finite nonzero number will always result in infinity, regardless of whether the finite number is positive or negative.

Multiplying two infinite values will also yield infinity.

However, if either value is 0, the result is undefined. Examples are as follows:

positive_inf = math.inf
negative_inf = -np.inf

print(2 * positive_inf)
print(0 * negative_inf)
print(positive_inf * negative_inf)



4. Division

Dividing a finite number by an infinite value will always result in 0. The outcome of dividing an infinite value by a finite one depends on the signs of the values involved.

Dividing one infinite value by another yields an undefined result (NaN). Let’s look at some examples:

import numpy as np

positive_inf = np.inf
negative_inf = -np.inf

print(positive_inf/ 2)



5. Comparison

When you want to compare values to positive or negative infinity in Python, you can simply use the standard comparison operators (<, <=, >, >=). For example:

a = float("inf")
b = 1000

if b < a:
    print("1000 is less than infinity")
    print("1000 is not less than infinity")


1000 is less than infinity

Now that we’ve gone over the fundamentals, let’s discuss how you can check whether a number is an infinite number in Python.

How to Check if a Number is an Infinite Number in Python

Infinity Symbol

When working with numbers in Python, you might encounter a scenario where you need to check if a number is infinite or not. You can do this using the isinf() function that the math module provides.

This function is a useful tool that can be used to identify positive or negative infinity in a variable. Let’s look at an example:

import math

positive_infinity = float('inf')
negative_infinity = float('-inf')




The above example demonstrates how the isinf() method returns a boolean value indicating if a given value is infinite.

You can also use the np.isinf() function from the NumPy library to perform this check. This function works for both variables and sequences like lists and DataFrames.

Practical Applications of Infinity in Python

Applications of infinity numeric values

Infinity, a concept that transcends mere numbers, has practical applications in Python that might surprise many developers.

This next section will explore the various ways in which infinity is utilized in real-world Python code.

1. Algorithms

In the field of algorithms, infinity is often used as a stand-in for the concept of the largest possible value or an unbounded upper limit.

This can be helpful in many computer science contexts, such as in graph algorithms.

Infinity can help ensure a smooth comparison process when:

  • finding the minimum or maximum value in a sequence of numbers
  • or, initializing the initial minimum or maximum value to positive or negative infinity

This approach can be particularly useful when working with dynamic data sets where the range of numbers might be unknown.

Here’s an example using Python’s built-in min() and max() functions to find the minimum and maximum values of a list, initialized with positive and negative infinity:

numbers = [3, 10, -5, 8]

min_value = float('inf')
max_value = float('-inf')

for num in numbers:
    min_value = min(min_value, num)
    max_value = max(max_value, num)

print('Minimum:', min_value)
print('Maximum:', max_value)

By using infinity (instead of arbitrarily large finite numbers), you can ensure that the algorithms will work consistently regardless of the specific details of the input graph.

2. Computation

When working with floating-point numbers, the concept of infinity plays an important role due to the limitations of finite precision arithmetic.

For instance, when performing numerical optimizations, these infinite values can be utilized to establish unbounded domains or to handle calculations that diverge.

In the realm of complex analysis, using infinity as a concept has practical implications in solving problems that involve limits and continuous functions.

For example, considering a point of “infinity” on a plane or sphere helps when reasoning about the properties of these mathematical objects and various transformations applied to them.

You can see an example in this video on how to convert continuous data into categorical in Power BI using Python:

By employing infinity in algorithms and computation across various fields of computer science, developers can utilize its properties to design effective and robust solutions to complex problems.

Final Thoughts

Infinity in Python is not merely an abstract mathematical concept but a functional tool that can simplify certain coding tasks and algorithms.

Grasping how to work with infinite numbers in Python is a foundational skill.

With the various techniques above, you’re now equipped to handle limitless numerical scenarios accurately.

Armed with these methods, we’re sure you’ll be able to confidently manage the concept of infinity while coding in Python.

If you enjoyed this guide, you can also check out our article on Python String to Int: A Guide to Convert Easily.

Frequently Asked Questions

What is NaN in Python?

In some cases, operations in Python may result in values that are not representable as numbers.

These values are called NaN (Not a Number) and often occur during arithmetic computations involving infinity or undefined mathematical expressions:

import numpy as np

result = 0.0 / 0.0



In this example, using numpy, we divided 0.0 by 0.0, which resulted in a NaN value. The numpy.isnan() method helps to check if a value is a NaN.

Handling infinite values and NaN values effectively is crucial for robust performance in data science and mathematical applications.

What is the max integer value in Python?

In Python, the maximum integer value is determined by the sys.maxsize constant. This constant varies depending on the platform and word size of the host machine. To access it, you must import the sys module:

import sys

max_int = sys.maxsize
print("Maximum integer value:", max_int)


Maximum integer value: 9223372036854775807

How to create an infinite set in Python

Python does not have a built-in way to create an infinite set.

However, you can use a generator expression to simulate an infinite set.

For example, here’s an infinite set of natural numbers using a generator:

def natural_numbers():
    n = 1
    while True:
        yield n
        n += 1

infinite_set = natural_numbers()
author avatar
Sam McKay, CFA
Sam is Enterprise DNA's CEO & Founder. He helps individuals and organizations develop data driven cultures and create enterprise value by delivering business intelligence training and education.

Related Posts