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.
The function syntax is as shown in the code snippet below:
Let us explore various function parameters as shown:
- x1 – represents the mod function’s input array whose elements are treated as dividends.
- x2 – the input array whose elements act as the divisors in the mod operation.
- out – this optional parameter defines an alternative path where the resulting array is stored.
- where – specifies the condition broadcasted over the input at a given location where the set condition is true.
- **kwargs – represents keyword arguments
Function Return Value
The function returns the element-wise remainder of the division between the specified arrays.
The code snippet below shows how to use the mod() function in a NumPy 1D array.
- We start by importing the NumPy package.
- Second, we create an array called x1 that acts as the ‘dividend array.’ This is a simple 1D array.
- Third, we create another 1D array that acts as the ‘divisor array.’
- 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).
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:
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:
Let us see how the function behaves in a multi-dimensional array. Example code is illustrated below:
The resulting array is:
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!!