Compute the Reciprocal for all elements in a NumPy array


The reciprocal of a number is defined as the multiplicative inverse of that number, when we have a non-zero number ‘a’ then the reciprocal of ‘a’ will be ‘b’, Hence, a * b = 1. In other words, reciprocal of ‘a’ is given as ‘1/a’.

The reciprocal() function

We can calculate the reciprocal of an array using the reciprocal() function of the Numpy library. This function accepts an array as a parameter and returns the reciprocal of the elements of the given array. The within the same shape and size of the original array.

Syntax

Following is the syntax for applying the reciprocal() function to an array.

numpy.reciprocal(x, out=None)

Where,

  • x is an input array.

  • out is an optional parameter representing the location to store the resultant array. It must have the same shape as the input array. If this value is not provided a new array is created and the resultant vales are stored in it.

Example

In the following example, In order to calculate the reciprocal of the given input array, we are passing the array as an argument to the reciprocal() function.

import numpy as np
a = np.array([34,23,90,34,100])
print("The input array:",a)
print("The dimension of the array:",np.ndim(a))
reci = np.reciprocal(a,dtype = float)
print("The reciprocal of the given 1-d array:",reci)

Output

The input array: [ 34 23 90 34 100]
The dimension of the array: 1
The reciprocal of the given 1-d array: [0.02941176 0.04347826 0.01111111 0.02941176 0.01 ]

Example

In the following example, we shall not mention data type, so by default the data type of the output array will be integer and no float values will be returned.

import numpy as np
a = np.array([34,23,90,34,100])
print("The input array:",a)
print("The dimension of the array:",np.ndim(a))
reci = np.reciprocal(a)
print("The reciprocal of the given 1-d array:",reci)

Output

The input array: [ 34 23 90 34 100]
The dimension of the array: 1
The reciprocal of the given 1-d array: [0 0 0 0 0]

Example

This is one more example which uses the reciprocal function for calculating the reciprocal of the 2-d array elements.

import numpy as np
a = np.array([[34,23],[90,34]])
print("The input array:",a)
print("The dimension of the array:",np.ndim(a))
reci = np.reciprocal(a,dtype = float)
print("The reciprocal of the given 2-d array:",reci)

Output

The input array: [[34 23]
[90 34]]
The dimension of the array: 2
The reciprocal of the given 2-d array: [[0.02941176 0.04347826]
[0.01111111 0.02941176]]

Note

The reciprocal() function output array elements by default belongs to the int data type, so in some cases we will see only zeros as the output. If we want to display the entire float number as the output then we have to mention the data type as float in the reciprocal() function along with the array input.

Updated on: 09-Aug-2023

144 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements