NumPy Arithmetic Functions | Tutorial
NumPy Arithmetic Functions
NumPy arithmetic functions include simple addition, subtraction, multiplication, and division: add(), subtract(), multiply(), and divide().
It is important to note that the arrays must have the same shape or conform to the array broadcasting rules.
Example
import numpy as np
a = np.arange(9, dtype = np.float_).reshape(3,3)
print('First array:')
print(a)
print('n')
print('Second array:')
b = np.array([10,10,10])
print(b)
print('n')
print('Addition of the two arrays:')
print(np.add(a,b))
print('n')
print('Subtraction of the two arrays:')
print(np.subtract(a,b))
print('n')
print('Multiplication of the two arrays:')
print(np.multiply(a,b))
print('n')
print('Division of the two arrays:')
print(np.divide(a,b))
The output result is:
First array:
[[0. 1. 2.]
[3. 4. 5.]
[6. 7. 8.]]
Second array:
Addition of the two arrays:
[[10. 11. 12.]
[13. 14. 15.]
[16. 17. 18.]]
Subtraction of the two arrays:
[[-10. -9. -8.]
[ -7. -6. -5.]
[ -4. -3. -2.]]
Multiplication of the two arrays:
[[ 0. 10. 20.]
[30. 40. 50.]
[60. 70. 80.]]
Division of the two arrays:
[[0. 0.1 0.2]
[0.3 0.4 0.5]
[0.6 0.7 0.8]]
Additionally, NumPy includes other important arithmetic functions.
numpy.reciprocal()
The numpy.reciprocal() function returns the reciprocal of the elements, element-wise. For example, the reciprocal of 1/4 is 4/1.
Example
import numpy as np
a = np.array([0.25, 1.33, 1, 100])
print('Our array is:')
print(a)
print('n')
print('Calling reciprocal function:')
print(np.reciprocal(a))
The output result is:
Our array is:
[ 0.25 1.33 1. 100. ]
Calling reciprocal function:
[4. 0.7518797 1. 0.01 ]
numpy.power()
The numpy.power() function treats elements from the first input array as the base and computes it raised to the power of the corresponding element from the second input array.
Example
import numpy as np
a = np.array([10,100,1000])
print('Our array is:')
print(a)
print('n')
print('Calling power function:')
print(np.power(a,2))
print('n')
print('Second array:')
b = np.array([1,2,3])
print(b)
print('n')
print('Again calling power function:')
print(np.power(a,b))
The output result is:
Our array is:
Calling power function:
Second array:
Again calling power function:
numpy.mod()
numpy.mod() computes the remainder of the division of corresponding elements in the input arrays. The function numpy.remainder() also produces the same result.
Example
import numpy as np
a = np.array([10,20,30])
b = np.array([3,5,7])
print('First array:')
print(a)
print('n')
print('Second array:')
print(b)
print('n')
print('Calling mod() function:')
print(np.mod(a,b))
print('n')
print('Calling remainder() function:')
print(np.remainder(a,b))
The output result is:
First array:
Second array:
Calling mod() function:
Calling remainder() function:
YouTip