The isinf() function of NumPy

The isinf() function of NumPy module, checks each element of an ndarray or a NumPy array-like for infinity and returns the results as an ndarray containing Boolean values (True and False).

Logical Operations Updated 21 Oct 2024 1 min read

Overview

  • The numpy.isinf() function checks each element of a NumPy array-like for infinity and returns the results as an ndarray containing Boolean values. When the input is a scalar it returns a single Boolean value.
  • The numpy.isinf() function returns True for both positive infinity and negative infinity. For "Not a number(nan)" the function isinf() will return False.

Example

python
# Example Python program that checks the

            # elements of an array-like for infinity

            # excluding Not a Number

            import numpy

array_nd = numpy.ndarray(shape = (2, 2))

array_nd[0][0] = numpy.nan

            array_nd[0][1] = -numpy.inf # Negative infinity

            array_nd[1][0] = numpy.inf + 1

            array_nd[1][1] = 22/7

print("Contents of the ndarray:")

            print(array_nd)

print("Is an element infinity:")

            results = numpy.isinf(array_nd)

            print(results)

Output

Output
Contents of the ndarray:

[[       nan       -inf]

 [       inf 3.14285714]]

Is an element infinity:

[[False  True]

 [ True False]]

Example 2

python
# Example Python program that checks the

            # different scalars for infiniti

            import numpy

# Check a complex number for infiniti

            aComplexNumber = complex(1, 2)

            infResult = numpy.isinf(aComplexNumber)

            print(infResult)

# Check a float for infiniti

            aRealNumber = 1.99999999999999999999999999999999999999999999999999999999

            print(type(aRealNumber))

            infResult = numpy.isinf(aRealNumber)

            print(infResult)

# Check googol for infiniti

            googol = pow(10, 100)

            print("Googol:")

            print(googol)

            infResult = numpy.isinf(googol)

            print(infResult)

Output

Output
False

<class 'float'>

False

Googol:

10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

Traceback (most recent call last):

  File "/Users/vinodh/PythonProgs/np_isinf_ex1.py", line 20, in <module>

    infResult = numpy.isinf(googol)

                ^^^^^^^^^^^^^^^^^^^

TypeError: ufunc 'isinf' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''