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

ParameterTypeDescription
x1array_likeDividend array.
x2array_likeDivisor array. Must be broadcastable to the shape of x1.
outndarray, None, or tuple of ndarray and None, optionalOptional output array to store results. If None, a new array is created.
wherearray_like, optionalBoolean mask specifying where to compute. Elements where where=False retain their original value.
castingstr, optionalDefines the casting behavior when computing the modulus.
orderstr, optionalMemory layout order of the output array.
dtypedata-type, optionalDefines the data type of the output array.
subokbool, optionalDetermines 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.