| by Arround The Web | No comments

NumPy np.mod

The NumPy mod function allows you to get the remainder of each element from the division of two elements.

This article will explore the mod function, its syntax, parameters, and examples that illustrate how the function behaves under different conditions.

Function Syntax

The function syntax is as shown in the code snippet below:

numpy.mod(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = <ufunc 'remainder'>

Let us explore various function parameters as shown:

Function Parameters

  1. x1 – represents the mod function’s input array whose elements are treated as dividends.
  2. x2 – the input array whose elements act as the divisors in the mod operation.
  3. out – this optional parameter defines an alternative path where the resulting array is stored.
  4. where – specifies the condition broadcasted over the input at a given location where the set condition is true.
  5. **kwargs – represents keyword arguments

Function Return Value

The function returns the element-wise remainder of the division between the specified arrays.

Example 1

The code snippet below shows how to use the mod() function in a NumPy 1D array.

import numpy as np
x1 = np.array([4,6,8])
x2 = np.array([3,2,5])
print(f"remainder array: {np.mod(x1, x2)}")
  1. We start by importing the NumPy package.
  2. Second, we create an array called x1 that acts as the ‘dividend array.’ This is a simple 1D array.
  3. Third, we create another 1D array that acts as the ‘divisor array.’
  4. Finally, we call the mod function and pass the required parameters.

The above operation should return an array containing the remainder of dividing x1 and x2 (element-wise).

Output:

remainder array: [1 0 3]

Example 2

Suppose you want to divide the elements in a specific array via a common divisor? In such a case, you can pass the parameter of x2 as a value.

For example, consider the code shown below:

x1 = np.array([4,6,8])
print(f"remainder array: {np.mod(x1, 2)}")

In the above example code, we have one array. We then use the mod function and pass the array as the first parameter (dividends) and the divisor as an integer value.

This should lead to each element in the array, x1, being divided by two and return the array as shown:

remainder array: [0 0 0]

Example 3

Let us see how the function behaves in a multi-dimensional array. Example code is illustrated below:

x1 = np.array([[10,23,34], [2,3,4]])
x2 = np.array([[23,45,85], [5,6,7]])
print(f"remainder array: {np.mod(x1, x2)}")

The resulting array is:

remainder array: [[10 23 34]
               [ 2  3  4]]

Conclusion

In this article, we explored the mod() function in NumPy and how to use it to get the element-wise remainder from the division of two arrays.

Thanks for reading!!

Share Button

Source: linuxhint.com

Leave a Reply