# -*- coding:utf-8 -*-
import numpy as np
# math
x = np.arange(1, 5).reshape(2, 2)
y = np.arange(5, 9).reshape(2, 2)
add = np.add(x, y) # x+y
subtract = np.subtract(x, y) # x-y
multiply = np.multiply(x, y) # x*y
divide = np.divide(x, y) # x/y
sqrt = np.sqrt(x) # 开平方根
print("add:\n", add, '\n')
print("subtract:\n", subtract, '\n')
print("multiply:\n", multiply, '\n')
print("divide:\n", divide, '\n')
print("sqrt:\n", sqrt, '\n')
# 均表示在各个相同的位置做运算,不是矩阵运算
# 矩阵运算
v = np.array([9, 10])
w = np.array([11, 12])
print("np.dot(v, w):\n", np.dot(v, w), '\n') # 等价于v.dot(w)
print("np.dot(x, v):\n", np.dot(x, v), '\n') # 等价于x.dot(v)
print("np.dot(x, y):\n", np.dot(x, y), '\n') # 等价于x.dot(y)
z = np.array([[1, 2], [3, 4]])
print("np.sum(z):\n", np.sum(z), '\n') # Compute sum of all elements; prints "10"
print("np.sum(z, axis=0):\n", np.sum(z, axis=0), '\n') # Compute sum of each column; prints "[4 6]"
print("np.sum(z, axis=1):\n", np.sum(z, axis=1), '\n') # Compute sum of each row; prints "[3 7]"
print("z.T:\n", z.T, "\n") # 转置
print("v.T:\n", v.T, '\n') # 不变
输出:
add:
[[ 6 8]
[10 12]]
subtract:
[[-4 -4]
[-4 -4]]
multiply:
[[ 5 12]
[21 32]]
divide:
[[ 0.2 0.33333333]
[ 0.42857143 0.5 ]]
sqrt:
[[ 1. 1.41421356]
[ 1.73205081 2. ]]
np.dot(v, w):
219
np.dot(x, v):
[29 67]
np.dot(x, y):
[[19 22]
[43 50]]
np.sum(z):
10
np.sum(z, axis=0):
[4 6]
np.sum(z, axis=1):
[3 7]
z.T:
[[1 3]
[2 4]]
v.T:
[ 9 10]
more:
https://docs.scipy.org/doc/numpy/reference/routines.math.html
https://docs.scipy.org/doc/numpy/reference/routines.array-manipulation.html