w3resource

NumPy: Compute the reciprocal for all elements in a given array

NumPy Mathematics: Exercise-39 with Solution

Write a NumPy program to compute the reciprocal for all elements in a given array.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating an array containing floating-point numbers
x = np.array([1., 2., .2, .3])

# Displaying the original array x
print("Original array: ")
print(x)

# Calculating the reciprocal of each element in array x using np.reciprocal()
r1 = np.reciprocal(x)

# Calculating the reciprocal of each element in array x using the reciprocal operator (1/x)
r2 = 1/x

# Checking if the results from np.reciprocal() and the reciprocal operator are equal using np.array_equal()
assert np.array_equal(r1, r2)

# Displaying the reciprocals for all elements of the array obtained using np.reciprocal()
print("Reciprocal for all elements of the said array:")
print(r1) 

Sample Output:

Original array: 
[1.  2.  0.2 0.3]
Reciprocal for all elements of the said array:
[1.         0.5        5.         3.33333333]

Explanation:

In the above code –

x = np.array([1., 2., .2, .3]): This line creates a NumPy array x with four float elements. The four elements in the array are 1.0, 2.0, 0.2, and 0.3.

r1 = np.reciprocal(x): np.reciprocal(x) returns the reciprocal of each element of the input array x. The reciprocal of an element x is defined as 1/x. For example, if x is [1., 2., .2, .3], then np.reciprocal(x) will return [1.,0.5, 5., 3.33333333]

r2 = 1/x: 1/x also calculates the reciprocal of each element in x. Since the operation 1/x is performed element-wise, it returns an array of the same shape as x with each element's reciprocal value.

assert np.array_equal(r1, r2): The resulting arrays from both methods, r1 and r2 respectively, are compared using np.array_equal() function to check if they have equal elements. As r1 and r2 are equal assert returns true.

Python-Numpy Code Editor:

Previous: Write a NumPy program to compute numerical negative value for all elements in a given array.

Next: Write a NumPy program to compute xy, element-wise where x, y are two given arrays.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-math-exercise-39.php