Open In App

Compute the Reciprocal for all elements in a NumPy array

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, let’s discuss how to compute the reciprocal for all the elements of a given NumPy array.

Method 1: Through reciprocal_arr = 1/arr  statement, we can convert every element of arr to it reciprocal and saved it to reciprocal_arr.But there is a catch, you will be encountered with an error if any element of “arr” be zero. So be careful not to pass any array to reciprocal_arr which contains 0.

Example 1:

Python




# PROGRAM TO FIND RECIPROCAL OF EACH
# ELEMENT OF NUMPY ARRAY
import numpy as np
 
lst = [22, 34, 65, 50, 7]
arr = np.array(lst)
reciprocal_arr = 1/arr
 
print(reciprocal_arr)


Output:

[0.04545455 0.02941176 0.01538462 0.02       0.14285714]

Example 2:

Python




# PROGRAM TO FIND RECIPROCAL OF EACH
# ELEMENT OF NUMPY ARRAY
import numpy as np
 
tup = (12, 87, 77, 90, 57, 34)
arr = np.array(tup)
reciprocal_arr = 1/arr
 
print(reciprocal_arr)


Output:

[0.08333333 0.01149425 0.01298701 0.01111111 0.01754386 0.02941176]

Method 2: Using the numpy.reciprocal() method

Numpy library also provides a simple method to find reciprocal of every element of the array. The reciprocal() method can be used easily to create a new array each contains reciprocal of each element.

Example 1:

Python3




#  program to compute the Reciprocal
# for all elements in a given array
# with the help of numpy.reciprocal()
import numpy as np
 
arr = [2, 1.5, 8, 9, 0.2]
reciprocal_arr = np.reciprocal(arr)
 
print(reciprocal_arr)


Output:

[0.5        0.66666667 0.125      0.11111111 5.        ]

Example 2:

Python3




#  program to compute the Reciprocal for
# all elements in a given array with the
# help of numpy.reciprocal()
import numpy as np
 
arr = (3, 6.5, 1, 5.9, 8)
reciprocal_arr = np.reciprocal(arr)
 
print(reciprocal_arr)


Output:

[0.33333333 0.15384615 1.         0.16949153 0.125     ]



Last Updated : 29 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads