Summary: Python Infinity is an undefined value (negative or positive) such that positive infinity is greater than while negative infinity is lesser than any other value in a given code. The numerous ways of using Python infinity are:
- Using
float('Inf')
andfloat('-Inf')
- Using the
math
module. - Using the
decimal
module. - Using the “Numpy” library.
- Using The Inifinity module.
Exercise: Try to find a number that’s greater than infinity! 😉
Overview
Infinite is a term derived from the Latin word ‘infinitas’ which means “without an end” or “boundless”. Similarly, infinity in Python is an undefined value that can either be positive or negative.
☞ Here’s a thumb rule about Python Infinity:
Positive Infinity > Any other value in a python code > Negative Infinity
Until now there is no way to represent infinity as an integer. However, you might want to have a look at the ways in which an integer value can be made greater than any other value in this Blog Tutorial.
Let’s explore the ways Infinity can be used in Python:
Method 1: Using float(‘Inf’) And float(‘-Inf’)
Infinity can be a positive or negative value as we mentioned in our thumb rule.
float('Inf')
is used to represent positive infinity.float('-Inf')
is used to represent negative infinity.
The following code demonstrates the implementation of positive and negative infinity:
infinity_positive = float('Inf') number = 9999999999999999999999999 if number > infinity_positive: print("number is greater than Infinity!") else: print("Positive Infinity is the greatest! Even greater than",number) infinity_negative = float('-Inf') if -number < infinity_negative: print("number is lesser than Negative Infinity!") else: print("Negative Infinity is the least! Even smaller than",-number)
Output:
Positive Infinity is the greatest! Even greater than 9999999999999999999999999 Negative Infinity is the least! Even smaller than -9999999999999999999999999
Method 2: Using Python Math Module
Python’s math module can also be used to implement infinity in Python 3.5 and above.
math.inf
is a predefined constant in Python that returns positive infinity.-math.inf
is a predefined constant in Python that returns negative infinity.
The following code demonstrates the implementation of infinity using the math module:
import math infinity_positive = math.inf number = 9999999999999999999999999 # Positive Infinity if number > infinity_positive: print("number is greater than Infinity!") else: print("Positive Infinity is the greatest! Even greater than",number) # Negative Infinity infinity_negative = -math.inf if -number < infinity_negative: print("number is lesser than Negative Infinity!") else: print("Negative Infinity is the least! Even smaller than",-number)
Output:
Positive Infinity is the greatest! Even greater than 9999999999999999999999999 Negative Infinity is the least! Even smaller than -9999999999999999999999999
Method 3: Using The Decimal Module
Another way of implementing infinity is by using Python’s decimal module which helps us to deal with fixed and floating-point arithmetic in Python.
-
Decimal(‘Infinity’)
returns positive infinity. -
Decimal(‘-Infinity’)
returns negative infinity.
The following code demonstrates the implementation of infinity using the math
module:
from decimal import Decimal infinity_positive = Decimal('Infinity') number = 9999999999999999999999999 # Positive Infinity if number > infinity_positive: print("number is greater than Infinity!") else: print("Positive Infinity is the greatest! Even greater than",number) # Negative Infinity infinity_negative = Decimal('-Infinity') if -number < infinity_negative: print("number is lesser than Negative Infinity!") else: print("Negative Infinity is the least! Even smaller than",-number)
Output:
Positive Infinity is the greatest! Even greater than 9999999999999999999999999 Negative Infinity is the least! Even smaller than -9999999999999999999999999
Method 4: Using The “Numpy” Library
Another popular way of implementing Infinity in Python is by using Python’s Numpy library. Numpy has its own definitions for infinite values.
np.inf
returns positive infinity.-np.inf
returns negative infinity.
The following code demonstrates the implementation of infinity using the math module:
import numpy as np infinity_positive = np.inf number = 9999999999999999999999999 # Positive Infinity if number > infinity_positive: print("number is greater than Infinity!") else: print("Positive Infinity is the greatest! Even greater than",number) # Negative Infinity infinity_negative = -np.inf if -number < infinity_negative: print("number is lesser than Negative Infinity!") else: print("Negative Infinity is the least! Even smaller than",-number)
Output:
Positive Infinity is the greatest! Even greater than 9999999999999999999999999 Negative Infinity is the least! Even smaller than -9999999999999999999999999
Method 5: Using The Inifinity Module
The all-in-one infinity value module designed by Konsta Vesterinen can be compared to any object. That means it overcomes the limitations of being able to compare only float values. When we try to compute pow(1, float('inf'))
returns 1. Frankly speaking, this should not be the case, as it should be undefined. When you use the infinity module it returns a type error
in this case instead of returning 1 which is more acceptable and realistic.
Since infinity is not a part of Python’s standard library. So, before using it, you must install it using the following command:
pip install infinity
Let us have a look at the following code to understand how the Infinity class works:
from infinity import inf number = 9999999999999999999999999 # Positive Infinity if number > inf: print("number is greater than Infinity!") else: print("Positive Infinity is the greatest! Even greater than",number) # Negative Infinity infinity_negative = -inf if -number < infinity_negative: print("number is lesser than Negative Infinity!") else: print("Negative Infinity is the least! Even smaller than",-number)
Output
Positive Infinity is the greatest! Even greater than 9999999999999999999999999 Negative Infinity is the least! Even smaller than -9999999999999999999999999
Having learned numerous ways of implementing infinity in python, let us have a look at few operations that can be performed using python infinity.
Infinity Arithmetic
Generally, most arithmetic operations performed on infinity values result in generation of other infinite values. The following example illustrates this concept :
value = float('inf') print('Result of Addition : ',value + 15) print('Result of Subtraction : ',value - 15) print('Result of Multiplication : ',value * 15) print('Result of Division : ',value / 15) #special scenario print('Multiplication by Zero: ',value * 0)
Output:
Result of Addition: inf Result of Subtraction: inf Result of Multiplication: inf Result of Division: inf Multiplication by Zero: nan
Note:
- Division by zero raises a
ZeroDivisionError
exception instead of yielding a resultant value. - Arithmetic operations on
NaN
always giveNaN
. There is no “negative NaN”.
Python Infinity Check
The isinf()
method of the math module is used to check for infinite values in Python. The following example demonstrates this concept :
import numpy as np import math num1 = np.inf num2 = -np.inf num3 = 25 print("Is num1 an infinite number?: ",math.isinf(num1)) print("Is num3 an infinite number?: ",math.isinf(num2)) print("Is num2 an infinite number?: ",math.isinf(num3))
Creating Arrays With Infinity Values
The following example demonstrates how an array of infinity values can be created:
import numpy as np # To create a numpy array with all values initialized to infinity array_infinity = np.full(5, np.inf) print('Infinite Array: ',array_infinity)
Output:
Infinite Array: [ inf inf inf inf inf]
Test your knowledge based on the above explanations:
What will be the output of the following snippet?
import math a=float('-infinity') b=float('inf') print(a) print(b) print(math.inf) print(-math.inf)
Answers: Run the code to get the answers!
Why Use Python Infinity?
Infinity is majorly used in complex algorithmic designs and optimization problems. One such example is the Shortest Path Algorithm where the current distance values have to be compared with the best or the least distance values. It is extremely useful in comparison scenarios where it acts as an unbounded upper or lower value.
Let us have a look at a simple program that finds the cheapest path from a list of given options:
least_path_cost = float('inf') # Assume that these values were calculated using some xyz algorithm path_cost = [10, 100, 99999999999, 50] for path in path_cost: if path < least_path_cost: least_path_cost = path print("The Lowest Path is", least_path_cost)
Output
The Lowest Path is 10
If we did not have the positive infinity i.e. float(inf)
available to us, we would not have known the initial lowest_path_cost value in the code. Thus we see the importance of infinity
in python.
Conclusion
In this article, we covered numerous ways of dealing with Python infinity and I hope you found this article useful and it helps you to get started with the fundamentals of Python Infinity!
Please subscribe and stay tuned for more interesting articles in the future.
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.