NumPy: Get the element-wise remainder of an array of division
6. Element-wise Remainder (Modulo)
Write a NumPy program to get the element-wise remainder of an array of division.
Sample Solution:
Python Code:
# Importing the NumPy library
import numpy as np
# Creating an array from 0 to 6
x = np.arange(7)
# Displaying the original array
print("Original array:")
print(x)
# Computing the element-wise remainder of division by 5 and displaying the result
print("Element-wise remainder of division:")
print(np.remainder(x, 5))
Sample Output:
Original array: [0 1 2 3 4 5 6] Element-wise remainder of division: [0 1 2 3 4 0 1]
Explanation:
In the above code:
x = np.arange(7) – This line creates an array from 0 to 6. np.remainder(x, 5) – This line calculates the remainder of each element in x when divided by 5.
So, the result printed by print(np.remainder(x, 5)) will be [0, 1, 2, 3, 4, 0, 1].
For more Practice: Solve these Related Problems:
- Implement a function that calculates the modulus for corresponding elements of two arrays using np.mod.
- Test the element-wise remainder operation on arrays containing both positive and negative integers.
- Compare the outputs of np.mod and np.remainder to ensure they behave identically.
- Use broadcasting to compute the remainder when dividing an array by a scalar and verify the result.
Python-Numpy Code Editor:
Previous: Write a NumPy program to get the powers of an array values element-wise.Next: Write a NumPy program to calculate the absolute value element-wise.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics