w3resource

NumPy: Add, subtract, multiply, divide arguments element-wise


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:

NumPy Mathematics: Add, subtract, multiply, divide arguments element-wise

Python-Numpy Code Editor: