w3resource

NumPy: Test element-wise for positive or negative infinity.

NumPy: Basic Exercise-6 with Solution

Write a NumPy program to test elements-wise for positive or negative infinity.

Sample Solution :

Python Code :

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a NumPy array 'a' containing elements 1, 0, NaN (Not a Number), and infinity
a = np.array([1, 0, np.nan, np.inf])

# Printing the original array 'a'
print("Original array")
print(a)

# Testing the given array 'a' element-wise for positive or negative infinity and printing the result
print("Test element-wise for positive or negative infinity:")
print(np.isinf(a)) 

Sample Output:

Original array
[  1.   0.  nan  inf]
Test element-wise for positive or negative infinity:
[False False False  True]                         

Explanation:

In the above code –

np.array([1, 0, np.nan, np.inf]) creates a NumPy array ‘a’ with the elements 1, 0, NaN (Not a Number), and Inf (Infinity).

print(np.isinf(a)): The np.isinf() function tests element-wise if the values in the array 'a' are infinite. The function returns a boolean array of the same shape as 'a', with True for infinite values (Inf) and False for non-infinite values (1, 0, and NaN).

Pictorial Presentation:

NumPy: Test element-wise for positive or negative infinity.

Python-Numpy Code Editor:

Previous: Test a given array element-wise for finiteness (not infinity or not a Number).
Next: Test element-wise for NaN of a given array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.