Python Numpy Reciprocal Function [9 Easy Code Examples]

python numpy reciprocal function explained with easy python code examples in jupyter notebook

In this article, we’ll learn the Python Numpy reciprocal function in detail. We’ll go through the parameters of this function and understand them practically using code examples. The proper explanations for all those examples will be provided so your concepts got crystal clear.

Understanding Python Numpy Reciprocal Function

The role of the reciprocal function is to calculate the reciprocal of each item in the Numpy array passed to it as an argument. We can get the reciprocal by dividing 1 by that specific value i.e. 1/value.

python numpy reciprocal function explained with easy python code examples in jupyter notebook

 

reciprocal function of python numpy library

reciprocal function of python numpy library explained with code examples

reciprocal function of python numpy easy code examples

Syntax of numpy.reciprocal()

numpy.reciprocal(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, ufunc 'reciprocal')

Explanation of Reciprocal Parameters

  • The first parameter ‘x’ can be a one/multi-dimensional array or a scalar value. The reciprocal operations are performed on this data.
  • The parameter ‘out’ is optional. We can specify where we want to store the resulting output data by making use of this parameter. Make sure that the shape of the array passed to the ‘out’ parameter matches with the array on which the reciprocal operations will execute. If we don’t use it, then a new array will be created to store the result.
  • The parameter ‘where’ is optional. It consumes an array of Boolean values. During execution, when the item is True then the reciprocal will be performed, else it won’t process.
  • The ‘casting’ parameter is also optional. The role of this parameter is to specify which kind of data casting should be allowed during the execution operation. The values it takes can be ‘equiv’, ‘safe’, ‘no’, ‘same_kind’, or ‘unsafe’. The default value passed to this parameter is ‘same_kind’.
  • The parameter ‘order’ is also set to be optional. It just sets the output array’s memory layout. The values we can pass to it can be ‘C’(C-style contiguous), ‘A’(any), or ‘F’(Fortran-style contiguous).
  • The optional parameter ‘dtype’ is used to set the data type of the resulting array. If it’s not specified, the datatype will be taken by the input array item’s datatype.

Practical Explanation of numpy.reciprocal() Function (9 Examples)

Example 1: Reciprocal of 1D Array

import numpy as np

ar1D = np.array([11, 5, 3, 0.7,54])
result = np.reciprocal(ar1D)
print(result)

Output

[0.09090909 0.2        0.33333333 1.42857143 0.01851852]

In this code example:

  • We first imported the numpy library. If you don’t have it inside your system then run (pip install numpy) in your terminal and then import it as specified above.
  • Secondly, a one-dimensional array has been created.
  • After that, we passed this array as an argument to the reciprocal function and stored it inside a variable.
  • The output shows that all the items of the input array have gone through the reciprocal operation and the results were stored inside the new array.

Example 2: Apply reciprocal() to an array having zeros

ar = np.array([1,6,3,0,5.7,0,2])

res = np.reciprocal(ar)
print(res)

Output

[1.   0.16666667   0.33333333    inf    0.1754386     inf    0.5    ]

We applied the reciprocal function on an array of which some elements are 0. The output shows that performing the reciprocal operation on 0 results in inf(infinity) along with a warning that you’ll see when you run it. The reason is that dividing directly by zero in Python results in raising a ‘ZeroDivisionError‘ but it’s handled by the numpy.reciprocal() function and returns inf(infinity) in its place.

Example 3: Apply reciprocal on 2D Array

ar2Dim = np.array([[4,1],[5,2.4],[9,0.0]])

resul = np.reciprocal(ar2Dim)
print(resul)

Output

[[0.25       1.        ]
 [0.2        0.41666667]
 [0.11111111        inf]]

In this code, the 2D array has been used for the reciprocal operation. The output shows that all the items of the 2D array have been successfully used in reciprocal operation and the result is stored in the array shown in the output block.

Example 4: numpy.reciprocal on a Scalar Value

scValue=11.3
r=np.reciprocal(scValue)
print(r)

Output

0.08849557522123894

In this code, we passed a scalar value to the reciprocal function and it performed the specified operation in it. The result can be seen in the output section.

Example 5: Specifying Parameter ‘out’

xArr = np.array([2.3,8.5,4,9])
output = np.empty_like(xArr)

np.reciprocal(xArr, out=output)
print(output)

Output

[0.43478261 0.11764706 0.25       0.11111111]

In this example:

We first created a 1D array. Then we created an empty array using ‘empty_like’ function and passed it the first array(xArr) as an argument so it can have the same shape as the first array.

Then we passed the first 1D array to the reciprocal function. Also, we specified the ‘out‘ parameter and passed it the empty array that we created. It will store the result in the output(empty array having the same shape as xArr) after applying the reciprocal operation on the input array(xArr).

Example 6: Parameter ‘where’ of reciprocal Function

arr = np.array([6, 0,8.5, 0,3])
whereMask = arr != 0 # Create a mask where non-zero elements are True

# Reciprocal calculation for all elements
resultSimple=np.reciprocal(arr)

# Reciprocal calculation for only non-zero elements
resultWhere = np.reciprocal(arr, where=whereMask)

print('Simple result')
print(resultSimple)

print('Result with where parameter specified')
print(resultWhere)

Output

Simple result
[0.16666667        inf 0.11764706        inf 0.33333333]
Result with where parameter specifiying perform actions for non zeros items only
[0.16666667        inf 0.11764706        inf 0.33333333]

In this code example:

  1. First, we created a simple array. Also, we created an array that will have Boolean items. The item will be True if the first array(arr) is nonzero and it’ll be false if the item is zero.
  2. Then we passed the array(arr) to the reciprocal function.
  3. We’ve also passed the boolean items array to the ‘where‘ parameter of the reciprocal. During the reciprocal operation, each item of the array that is passed to where the parameter will be checked. If it’s true then the operation of reciprocal will be performed, if false then this operation won’t be executed.
  4. For a complete demonstration, we’ve created two outputs. The first one is without specifying the ‘where‘ parameter and the second one includes specifying the ‘where‘ parameter.

Example 7: Demonstration of ‘casting’ Parameter

ar = np.array([2, 4, 6, 8], dtype=np.uint8) # Unsigned integer array
res = np.reciprocal(ar, casting='safe')

print(res)

Output

[0 0 0 0]

In this code, the array shows unsigned 8-bit integers as it is of data type ‘uint8‘. We’ve specified the ‘casting‘ parameter of reciprocal to be ‘safe‘ which sets the rule to disallow division by zero. The result is that all the reciprocal operations on the specified array (ar) become zero.

Example 8: ‘order’ Parameter Practical Explanation

array2D = np.array([[1, 2], [31, 8]])

res_c_order = np.reciprocal(array2D, order='C')
res_f_order = np.reciprocal(array2D, order='F')

print(res_c_order)
print(res_f_order)

Output

[[1 0]
 [0 0]]      #c order
[[1 0]
 [0 0]]      #f order

The order parameter is used to specify the memory layout for the resulting array. Passing it ‘C‘ will make it C style memory layout while ‘F‘ will specify it to be of Fortran style memory layout. Both these outputs are different and the reason is that both of them have different order styles.

Example 9: ‘dtype’ Parameter Demonstrated Practically

xArr = np.array([4, 7, 9, 20])

res_float = np.reciprocal(xArr, dtype=np.float32)
res_complex = np.reciprocal(xArr, dtype=np.complex64)

print(res_float) 
print(res_complex)

Output

[0.25       0.14285715 0.11111111 0.05      ] 
[0.25      -0.j 0.14285715-0.j 0.11111111-0.j 0.05      -0.j]

From this example, we can understand that specifying the ‘dtype’ parameter changes the output array. In the first example, we have provided ‘np.float32‘ to the ‘dtype‘ parameter while in the second example, we’ve given it ‘np.complex64‘. The 2 output arrays show different results for both.

Conclusion

In conclusion, we have practically learned the usage and implementation of the Python Numpy reciprocal function. The parameters of the reciprocal Numpy function were explained with multiple code examples.

Thank you for reading it.

Leave a Comment

Your email address will not be published. Required fields are marked *