NumPy Arithmetic Functions

NumPy arithmetic functions include simple addition, subtraction, multiplication, and division:add(),subtract(),multiply()anddivide()。

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))

The output result is:

第一个数组:
[[0. 1. 2.]
 [3. 4. 5.]
 [6. 7. 8.]]


第二个数组:
[10 10 10]


两个数组相加:
[[10. 11. 12.]
 [13. 14. 15.]
 [16. 17. 18.]]


两个数组相减:
[[-10.  -9.  -8.]
 [ -7.  -6.  -5.]
 [ -4.  -3.  -2.]]


两个数组相乘:
[[ 0. 10. 20.]
 [30. 40. 50.]
 [60. 70. 80.]]


两个数组相除:
[[0.  0.1 0.2]
 [0.3 0.4 0.5]
 [0.6 0.7 0.8]]

In addition, NumPy also contains other important arithmetic functions.

numpy.reciprocal()

The numpy.reciprocal() function returns the reciprocal of the argument element by element. For example,1/4The reciprocal is4/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 the reciprocal function:') print (np.reciprocal(a))

The output result is:

我们的数组是:
[  0.25   1.33   1.   100.  ]


调用 reciprocal 函数:
[4.        0.7518797 1.        0.01     ]

numpy.power()

The numpy.power() function takes the elements in the first input array as the base and calculates the power raised by the 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 the power function:') print (np.power(a,2)) print ('\n') print ('Second array:') b = np.array([1,2,3]) print (b) print ('\n') print ('Calling the power function again:') print (np.power(a,b))

The output result is:

我们的数组是;
[  10  100 1000]


调用 power 函数:
[    100   10000 1000000]


第二个数组:
[1 2 3]


再次调用 power 函数:
[        10      10000 1000000000]

numpy.mod()

numpy.mod() calculates the remainder after division of the 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 the mod() function:') print (np.mod(a,b)) print ('\n') print ('Calling the remainder() function:') print (np.remainder(a,b))

The output result is:

第一个数组:
[10 20 30]


第二个数组:
[3 5 7]


调用 mod() 函数:
[1 0 2]


调用 remainder() 函数:
[1 0 2]
Other Extensions