NumPy Arithmetic Functions
NumPy arithmetic functions include simple addition, subtraction, multiplication, and division: add(),subtract(),multiply() and divide()。
Note that arrays must have the same shape or comply with array broadcasting rules.
Example
import
numpy
as
np
a
=
np
.
arange
(
9
,
dtype
=
np
.
float_
)
.
reshape
(
3
,
3
)
(
'
The first array:
'
)
(
a
)
(
'
\n
'
)
(
'
The second array:
'
)
b
=
np
.
array
(
[
10
,
10
,
10
]
)
(
b
)
(
'
\n
'
)
(
'
Adding two arrays:
'
)
(
np
.
add
(
a
,
b
)
)
(
'
\n
'
)
(
'
Subtracting two arrays:
'
)
(
np
.
subtract
(
a
,
b
)
)
(
'
\n
'
)
(
'
Multiplying two arrays:
'
)
(
np
.
multiply
(
a
,
b
)
)
(
'
\n
'
)
(
'
Dividing two arrays:
'
)
(
np
.
divide
(
a
,
b
)
)
The output is:
第一个数组:
[[0. 1. 2.]
[3. 4. 5.]
[6. 7. 8.]]
Second array:
[10 10 10]
Adding two arrays:
[[10. 11. 12.]
[13. 14. 15.]
[16. 17. 18.]]
Array subtraction:
[[-10. -9. -8.]
[ -7. -6. -5.]
[ -4. -3. -2.]]
Multiplying two arrays:
[[ 0. 10. 20.]
[30. 40. 50.]
[60. 70. 80.]]
Divide two arrays:
[[0. 0.1 0.2]
[0.3 0.4 0.5]
[0.6 0.7 0.8]]
In addition, Numpy also includes other important arithmetic functions.
numpy.reciprocal()
The numpy.reciprocal() function returns the element-wise reciprocal of the argument. For example, 1/4 the reciprocal is 4/1。
Example
import
numpy
as
np
a
=
np
.
array
(
[
0.25
,
1.33
,
1
,
100
]
)
(
'
Our array is:
'
)
(
a
)
(
'
\n
'
)
(
'
Calling the reciprocal function:
'
)
(
np
.
reciprocal
(
a
)
)
The output is:
我们的数组是:
[ 0.25 1.33 1. 100. ]
Call the reciprocal function:
[4. 0.7518797 1. 0.01 ]
numpy.power()
The numpy.power() function takes the elements in the first input array as bases and computes their powers with the corresponding elements in the second input array.
Example
import
numpy
as
np
a
=
np
.
array
(
[
10
,
100
,
1000
]
)
(
'
Our array is;
'
)
(
a
)
(
'
\n
'
)
(
'
Calling the power function:
'
)
(
np
.
power
(
a
,
2
)
)
(
'
\n
'
)
(
'
The second array:
'
)
b
=
np
.
array
(
[
1
,
2
,
3
]
)
(
b
)
(
'
\n
'
)
(
'
Calling the power function again:
'
)
(
np
.
power
(
a
,
b
)
)
The output is:
我们的数组是;
[ 10 100 1000]
Call the power function:
[ 100 10000 1000000]
Second array:
[1 2 3]
Call the power function again:
[ 10 10000 1000000000]
numpy.mod()
numpy.mod() computes the remainder after 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
]
)
(
'
The first array:
'
)
(
a
)
(
'
\n
'
)
(
'
The second array:
'
)
(
b
)
(
'
\n
'
)
(
'
Calling the mod() function:
'
)
(
np
.
mod
(
a
,
b
)
)
(
'
\n
'
)
(
'
Calling the remainder() function:
'
)
(
np
.
remainder
(
a
,
b
)
)
The output is:
第一个数组:
[10 20 30]
Second array:
[3 5 7]
Call the mod() function:
[1 0 2]
Call the remainder() function:
[1 0 2]