w3resource

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


39. Compute Reciprocals

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.


For more Practice: Solve these Related Problems:

  • Implement a function that computes the reciprocal (1/x) for each element in an array using np.reciprocal.
  • Test the function on an array with a mix of small and large values and handle division by zero appropriately.
  • Create a solution that compares the output of 1.0/array with np.reciprocal to ensure consistency.
  • Apply the function to a multi-dimensional array and verify that the reciprocal operation is applied element-wise.

Go to:


PREV : Compute Numerical Negation
NEXT : Element-wise Exponentiation (x^y)

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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.