NumPy: Add, subtract, multiply, divide arguments element-wise
1. Element-wise Arithmetic Operations
Write a NumPy program to add, subtract, multiply, divide arguments element-wise.
Sample elements: 4.0, 1.2
Sample Solution:
Python Code:
# Importing the NumPy library
import numpy as np
# Displaying a message for addition operation
print("Add:")
# Performing addition
print(np.add(1.0, 4.0))
# Displaying a message for subtraction operation
print("Subtract:")
# Performing subtraction
print(np.subtract(1.0, 4.0))
# Displaying a message for multiplication operation
print("Multiply:")
# Performing multiplication
print(np.multiply(1.0, 4.0))
# Displaying a message for division operation
print("Divide:")
# Performing division
print(np.divide(1.0, 4.0))
Sample Output:
Add: 5.0 Subtract: -3.0 Multiply: 4.0 Divide: 0.25
Explanation:
In the above exercise –
np.add(1.0, 4.0): Here NumPy's add() function is used to add the two numbers together, which in this case are 1.0 and 4.0. The result would be 5.0.
np.subtract(1.0, 4.0): Here NumPy's subtract() function is used to subtract the second number from the first one, which in this case are 1.0 and 4.0 respectively. The result would be -3.0.
np.multiply(1.0, 4.0): Here NumPy's multiply() function is used to multiply the two numbers together, which in this case are 1.0 and 4.0. The result would be 4.0.
np.divide(1.0, 4.0): Here NumPy's divide() function is used to divide the first number by the second one, which in this case are 1.0 and 4.0 respectively. The result would be 0.25.
Pictorial Presentation:
For more Practice: Solve these Related Problems:
- Implement element-wise arithmetic operations on two arrays with different shapes using broadcasting rules.
- Create a function that takes two arrays and returns their element-wise sum, difference, product, and quotient as a single result.
- Perform element-wise arithmetic on an array and a scalar, ensuring proper type promotion and broadcasting.
- Compute arithmetic operations on arrays containing negative values and zeros to test edge cases.
Python-Numpy Code Editor:
Previous: NumPy Math Exercises Home.Next: Write a NumPy program to compute logarithm of the sum of exponentiations of the inputs, sum of exponentiations of the inputs in base-2.
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