How to Work with Infinity in Python
Some of the times we need to use positive or negative infinity as a value. For example, it is used in algorithms where you need to compare the current solution to the best solution so far. Usually at the initiation step, we like to set the cost/value to positive or negative infinity to make sure no other value in our input would be bigger/smaller. Most programming languages provide a way to represent infinity, where it meets the following requirement:
∀ x ∈ N, -∞ <x < +∞
∀ x ∈ Z, -∞ < x < +∞
Meaning every natural number (positive integers, i.e., 0, 1, 2, …) is smaller than positive infinity (+∞) and all positive and negative integers (…, -2, -1, 0, 1, 2, …) are bigger than negative infinity (-∞) and smaller than positive infinity.
Want to read this story later? Save it in Journal.
One hack than you can do is to use one number of bigger/smaller than the max/min in your input (min-1/max+1), to get away with positive/negative infinity. However, there is a much better way of doing this in Python.
To represent positive and negative infinity:
# positive infinity
p_inf = float("inf")# negative infinity
n_inf = float("-inf")
To check if a value is infinite you can do the following:
# by using the math library (preferred way)
import mathmath.isinf(float("-inf")) #OUTPUT:True
math.isinf(float("inf")) #OUTPUT:True# by comparing to infinity
float("inf") == float("inf") #OUTPUT:True
float("-inf") == float("-inf") #OUTPUT:True