NumPy - Arithmetic Operations
Arithmetic operations are used for numerical computation and we can perform them on arrays using NumPy. With NumPy we can quickly add, subtract, multiply, divide and get power of elements in an array. NumPy performs these operations even with large amounts of data. In this article, weâll see at the basic arithmetic functions in NumPy and show how to use them for simple calculations.
1. Addition of Arrays
Addition is an arithmetic operation where the corresponding elements of two arrays are added together. In NumPy the addition of two arrays is done using the np.add() function.
import numpy as np
a = np.array([5, 72, 13, 100])
b = np.array([2, 5, 10, 30])
add_ans = np.add(a, b)
print(add_ans)
Output:
[ 7 77 23 130]
2. Subtraction of Arrays
We can subtract two arrays element-wise using the np.subtract() function. This function subtracts each element of the second array from the corresponding element in the first array.
import numpy as np
a = np.array([5, 72, 13, 100])
b = np.array([2, 5, 10, 30])
sub_ans = np.subtract(a, b)
print(sub_ans)
Output:
[ 3 67 3 70]
3. Multiplication of Arrays
Multiplication in NumPy can be done element-wise using the np.multiply() function. This multiplies corresponding elements of two arrays.
import numpy as np
a = np.array([5, 72, 13, 100])
b = np.array([2, 5, 10, 30])
mul_ans = np.multiply(a, b)
print(mul_ans)
Output:
[ 10 360 130 3000]
4. Division of Arrays
Division is another important operation that is performed element-wise using the np.divide() function. This divides each element of the first array by the corresponding element in the second array.
import numpy as np
a = np.array([5, 72, 13, 100])
b = np.array([2, 5, 10, 30])
div_ans = np.divide(a, b)
print(div_ans)
Output:
[ 2.5 14.4 1.3 3.33333333]
5. Exponentiation (Power)
It allows us to raise each element in an array to a specified power. In NumPy, this can be done using the np.power() function.
import numpy as np
a = np.array([5, 72, 13, 100])
b = np.array([2, 5, 10, 30])
pow_ans = np.power(a, b)
print(pow_ans)
Output:
[25 1934917632 137858491849 1152921504606846976]
6. Modulus Operation
It finds the remainder when one number is divided by another. In NumPy, you can use the np.mod() function to calculate the modulus element-wise between two arrays.
import numpy as np
a = np.array([5, 72, 13, 100])
b = np.array([2, 5, 10, 30])
mod_ans = np.mod(a, b)
print(mod_ans)
Output:
[ 1 2 3 10]
With these basic arithmetic functions in NumPy we can efficiently perform calculations on arrays.