NumPy: Add, subtract, multiply, divide arguments element-wise
NumPy Mathematics: Exercise-1 with Solution
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:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/numpy/python-numpy-math-exercise-1.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics