To check if a number is finite or not in Python, you can use the math module isfinite() function. isfinite() returns a boolean value which tells us if the input number is finite or not.
import math
print(math.isfinite(10))
print(math.isfinite(float('inf')))
#Output:
True
False
The Python math module has many powerful functions which make performing certain calculations in Python very easy.
One such piece of information which can be useful is if we want to check if a number is finite or infinite.
We can use the math module isfinite() function to check if a number is finite in our Python code.
isfinite() takes an integer or float input and returns a boolean. If the number passed is finite, isfinite() returns True. If the number passed is not finite, then isfinite() returns False.
Below are a few examples showing you how to use isfinite() in Python to check if a number is finite or not.
import math
print(math.isfinite(10))
print(math.isfinite(-10))
print(math.isfinite(1000000000000000000000))
print(math.isfinite(float('inf')))
print(math.isfinite(-float('inf')))
#Output:
True
True
True
False
False
How to Check if Number is Infinite in Python
If you want to go the other way and check if a number is infinite or equal to infinity, then you want to take the negation of what is returned from isfinite().
Below is a simple example which shows you how to check if a number is infinite in Python.
import math
def isinfinite(num):
return not math.isfinite(num)
print(isinfinite(10))
print(isinfinite(-10))
print(isinfinite(1000000000000000000000))
print(isinfinite(float('inf')))
print(isinfinite(-float('inf')))
#Output:
False
False
False
True
True
Hopefully this article has been useful for you to learn how to use the Python math module isfinite() function in your Python programs.