numpy 常用方法
numpy简介
NumPy(Numerical Python)是Python的一种开源的数值计算扩展。这种工具可用来存储和处理大型矩阵,比Python自身的嵌套列表(nested list structure)结构要高效的多(该结构也可以用来表示矩阵(matrix)),支持大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库。
安装numpy:
pip3 install --user numpy scipy matplotlib
示例代码
import numpy as np
'''
arr = np.random.random((3,4))
print(arr)
print(arr[1,2])
print(arr[0:2, 1:4])
# array operations
a = np.arange(5)
b = np.arange(0,10,2)
print("b="+str(b))
print("a^2 = "+str(a*a))
a = np.array([[1, 2], [3, 4]])
b = np.array([[1, 1], [2, 2]])
print(a)
print(b)
print("dot(a,b) = "+str(np.dot(a, b)))
'''
A = np.array([[1, 2], [3, 4]])
print(A.transpose())
print(np.linalg.inv(A))
#########################
# solve a linear system
# 2x + y - z = 0
# -3x - y + 2z = -11
# -2x + y +2z = -3
#
# solution :
# formulate AX = Y by listing A, Y
# find A-inverse
# calculate A-inverse dot Y, result in X
A = np.array([[2, 1, -1], [-3, -1, 2], [-2, 1, 2]])
Y = np.array([0, -11, -3])
A_inv = np.linalg.inv(A)
X = np.dot(A_inv, Y)
print("X = "+str(X))
# method 2:cal linalg.solve()
X = np.linalg.solve(A, Y)
print("X = "+str(X))
# SciPy: includes a lot of mathematical functions
import scipy.inter
|