NumPy mod()
The numpy.mod()
function returns the element-wise remainder of division.
It is equivalent to the Python modulus operator x1 % x2
and has the same sign as the divisor x2
.
Syntax
</>
Copy
numpy.mod(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True)
Parameters
Parameter | Type | Description |
---|---|---|
x1 | array_like | Dividend array. |
x2 | array_like | Divisor array. Must be broadcastable to the shape of x1 . |
out | ndarray, None, or tuple of ndarray and None, optional | Optional output array to store results. If None, a new array is created. |
where | array_like, optional | Boolean mask specifying where to compute. Elements where where=False retain their original value. |
casting | str, optional | Defines the casting behavior when computing the modulus. |
order | str, optional | Memory layout order of the output array. |
dtype | data-type, optional | Defines the data type of the output array. |
subok | bool, optional | Determines if subclasses of ndarray are preserved in the output. |
Return Value
Returns an array with the element-wise remainder after division. If both x1
and x2
are scalars, a scalar is returned.
Examples
1. Computing Modulus of Two Numbers
Here, we compute the modulus of two scalar values.
</>
Copy
import numpy as np
# Define dividend and divisor
x1 = 10
x2 = 3
# Compute modulus
result = np.mod(x1, x2)
# Print the result
print("10 mod 3 =", result)
Output:
10 mod 3 = 1

2. Modulus Operation on Arrays
We compute the modulus for two NumPy arrays.
</>
Copy
import numpy as np
# Define dividend and divisor arrays
x1 = np.array([10, 20, 30, 40, 50])
x2 = np.array([3, 4, 5, 6, 7])
# Compute modulus
result = np.mod(x1, x2)
# Print the results
print("Dividends:", x1)
print("Divisors:", x2)
print("Modulus:", result)
Output:
Dividends: [10 20 30 40 50]
Divisors: [3 4 5 6 7]
Modulus: [1 0 0 4 1]

3. Using the out
Parameter
Using an output array to store results instead of creating a new array.
</>
Copy
import numpy as np
# Define dividend and divisor arrays
x1 = np.array([15, 25, 35, 45])
x2 = np.array([4, 5, 6, 7])
# Create an output array
output_array = np.empty_like(x1)
# Compute modulus and store in output_array
np.mod(x1, x2, out=output_array)
# Print the results
print("Computed modulus:", output_array)
Output:
Computed modulus: [3 0 5 3]

4. Using the where
Parameter
Using a condition to compute modulus only for selected elements.
</>
Copy
import numpy as np
# Define dividend and divisor arrays
x1 = np.array([18, 27, 36, 45])
x2 = np.array([5, 4, 6, 7])
# Define a mask (compute modulus only where mask is True)
mask = np.array([True, False, True, False])
# Compute modulus values where mask is True
result = np.mod(x1, x2, where=mask)
# Print the results
print("Computed modulus with mask:", result)
Output:
Computed modulus with mask: [3 27 0 45]

The modulus values are computed only for elements where mask=True
.