Determine whether a NumPy array contains an infinity

By IncludeHelp Last updated : November 25, 2023

Problem Statement

Given a NumPy array, write a Python program to determine whether it contains an infinity (np.inf or -np.inf) or not.

Solution

To determine whether a NumPy array contains an infinity, use numpy.isinf() and any() method. Call the numpy.isinf() method, pass the array name, and then use .any() method. This will return True if the given array has an infinity; False, otherwise.

Example

Python program to determine whether a NumPy array contains an infinity.

# Importing numpy library
import numpy as np

# Creating two arrays
arr1 = np.array([1, 2, 3, np.inf, 5])
arr2 = np.array([1, 2, 3, 10, 5])

# Printing arrays
print("arr1\n", arr1, "\n")
print("arr2\n", arr2, "\n")

if np.isinf(arr1).any():
    print("arr1 has an infinity")
else:
    print("arr1 does not has an infinity")

if np.isinf(arr2).any():
    print("arr2 has an infinity")
else:
    print("arr2 does not has an infinity")

Output

The output of the above example is:

arr1
 [ 1.  2.  3. inf  5.] 

arr2
 [ 1  2  3 10  5] 

arr1 has an infinity
arr2 does not has an infinity

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.