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('Adding the two arrays:')
print(np.add(a, b))
print('\n')
print('Subtracting the two arrays:')
print(np.subtract(a, b))
print('\n')
print('Multiplying the two arrays:')
print(np.multiply(a, b))
print('\n')
print('Dividing the two arrays:')
print(np.divide(a, b))
Output:
First array:
[[0. 1. 2.]
[3. 4. 5.]
[6. 7. 8.]]
Second array:
[10 10 10]
Adding the two arrays:
[[10. 11. 12.]
[13. 14. 15.]
[16. 17. 18.]]
Subtracting the two arrays:
[[-10. -9. -8.]
[ -7. -6. -5.]
[ -4. -3. -2.]]
Multiplying the two arrays:
[[ 0. 10. 20.]
[30. 40. 50.]
[60. 70. 80.]]
Dividing 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 element-wise reciprocal of the argument. For example, 1/4 becomes 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))
Output:
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 in the first input array as base and computes their power with corresponding elements in 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('Calling power function again:')
print(np.power(a, b))
Output:
Our array is:
[ 10 100 1000]
Calling power function:
[ 100 10000 1000000]
Second array:
[1 2 3]
Calling power function again:
[ 10 10000 1000000000]
numpy.mod()
The numpy.mod() function computes the remainder of division of the elements in the input array. The numpy.remainder() function 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))
Output:
First array:
[10 20 30]
Second array:
[3 5 7]
Calling mod() function:
[1 0 2]
Calling remainder() function:
[1 0 2]
Calling the remainder() function: [1 0 2]