Use of math.isfinite() method in Python

In this article, we are going to learn the use of math.isfinite() method in Python. This is an inbuilt function of one of the popular module named math in Python. isfinite() returns the only boolean value for any argument passed inside the function.

The main motto of this function is to check whether the given argument(in the form of int, float, finite, infinite, NaN) is finite or infinite. If the given argument is infinite or NaN then it returns False else it returns True.

Syntax of math.isfinite() method

math.isfinite(x)

where x = a number which has to be checked whether the given number is finite or infinite, and it returns the Boolean value (True or False).

Let’s understand with some example:-

Simple way to check a number is finite or infinite in Python

import math
a = 6
b = 7.54
c = 8+0.54
d = 0*4
e = float("inf")
f = float("NaN")

print(math.isfinite(a))
print(math.isfinite(b))
print(math.isfinite(c))
print(math.isfinite(d))
print(math.isfinite(e))
print(math.isfinite(f))

Output:-

True
True
True
True
False
False

In this example, we imported the required module math of Python in which this inbuilt function is present. Then we created the 6 variable and stored a fixed value to each variable. And then we checked whether the given value is finite or infinite by using the method math.isfinite(), this method returns the boolean value for each value.

Checking whether the given number is finite or not from the list

import math
list = [7,9.8435,0.0,float("-inf"),float("NaN"),5/3]
for i in list:
    print(math.isfinite(i))

Output:-

True
True
True
False
False
True

The explanation for this example is as same as the previous example, the only difference is that we first stored some value in a list then we iterated through the list to check whether the given number is finite or not.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *