Test finiteness (not infinity and not Not a Number) in Numpy


To test for finiteness, use the numpy.isfinite() method in Python Numpy. Returns True where x is not positive infinity, negative infinity, or NaN; false otherwise. This is a scalar if x is a scalar.

This condition is broadcast over the input. At locations where the condition is True, the out array will be set to the ufunc result. Elsewhere, the out array will retain its original value. Note that if an uninitialized out array is created via the default out=None, locations within it where the condition is False will remain uninitialized.

Steps

At first, import the required library −

import numpy as np

To test for finiteness, use the numpy.isfinite() method in Python Numpy. Checking for numbers −

print("Finite? ", np.isfinite(1))
print("
Finite? ", np.isfinite(0))

Checking for float −

print("
Finite? ", np.isfinite(14.)) print("
Finite? ", np.isfinite(3.6))

Checking for NaN −

print("
Finite? ", np.isfinite(np.nan)) print("
Finite? ", np.isfinite(np.NAN))

Checking for infinity −

print("
Finite? ", np.isfinite(np.inf)) print("
Finite? ", np.isfinite(np.NINF))

Checking for log −

print("
Finite? ", np.isfinite(np.log(1))) print("
Finite? ", np.isfinite(np.log(2)))

Example

import numpy as np

# To test for finiteness, use the numpy.isfinite() method in Python Numpy

# Checking for numbers
print("Finite? ", np.isfinite(1))
print("
Finite? ", np.isfinite(0)) # Checking for float print("
Finite? ", np.isfinite(14.)) print("
Finite? ", np.isfinite(3.6)) # Checking for NaN print("
Finite? ", np.isfinite(np.nan)) print("
Finite? ", np.isfinite(np.NAN)) # Checking for infinity print("
Finite? ", np.isfinite(np.inf)) print("
Finite? ", np.isfinite(np.NINF)) # Checking for log print("
Finite? ", np.isfinite(np.log(1))) print("
Finite? ", np.isfinite(np.log(2)))

Output

Finite? True

Finite? True

Finite? True

Finite? True

Finite? False

Finite? False

Finite? False

Finite? False

Finite? True

Finite? True

Updated on: 08-Feb-2022

487 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements