python解决线性代数问题

###转置
import numpy as np
import pandas as pd
a=np.array([[1,2,3],[4,5,6],[7,8,9]])
b=np.array([[1,2,1],[4,5,3],[8,1,6]])
print(a)
print(a.T)#A的转置
print(a.T.T)#A的转置的转置还是A本身
[[1 2 3]
 [4 5 6]
 [7 8 9]]
[[1 4 7]
 [2 5 8]
 [3 6 9]]
[[1 2 3]
 [4 5 6]
 [7 8 9]]
##验证矩阵转置的性质:(A±B)'=A'±B'
print((a+b).T)
print((a.T+b.T))
[[ 2  8 15]
 [ 4 10  9]
 [ 4  9 15]]
[[ 2  8 15]
 [ 4 10  9]
 [ 4  9 15]]
#验证矩阵转置的性质:(KA)'=KA'
print((10*a).T)
print(10*(a.T))
[[10 40 70]
 [20 50 80]
 [30 60 90]]
[[10 40 70]
 [20 50 80]
 [30 60 90]]
print('a')
print(a)
print('b')
print(b)
print('a*b')
print((a*b))#位置相同相乘

#矩阵相乘
print(np.dot(a,b))#行列相称
a
[[1 2 3]
 [4 5 6]
 [7 8 9]]
b
[[1 2 1]
 [4 5 3]
 [8 1 6]]
a*b
[[ 1  4  3]
 [16 25 18]
 [56  8 54]]
[[ 33  15  25]
 [ 72  39  55]
 [111  63  85]]

方阵的迹就是主对角元素之和,使用trace()函数获得方阵的迹:

和的迹 等于 迹的和

print(a)
np.trace(a)
[[1 2 3]
 [4 5 6]
 [7 8 9]]

Out[5]:

计算行列式

15
a=np.array([[1,2],[3,4]])
print(a)
print(np.linalg.det(a))
[[1 2]
 [3 4]]
-2.0000000000000004

求可逆矩阵 linalg.inv

np.linalg.inv(a)
array([[-2. ,  1. ],
       [ 1.5, -0.5]])

np.linalg.solve()解一元线性方程组

#  x + 2y = 3
#  4x + 5y = 6
import numpy as np
A = np.mat('1,2; 4,5')    # 构造系数矩阵 A
b = np.mat('3,6').T       # 构造转置矩阵 b (这里必须为列向量)
r = np.linalg.solve(A,b)  # 调用 solve 函数求解

求特征值、特征向量。求矩阵的秩

x = np.diag((1, 6, 3))#创建一个对角矩阵!
print('x')
print(x)
a,b = np.linalg.eig(x)#特征值保存在a中,特征向量保存在b中
print('特征值a')
print(a)#特征值

print('特征向量b')
print(b)#特征向量 
np.linalg.matrix_rank(x)
x
[[1 0 0]
 [0 6 0]
 [0 0 3]]
特征值a
[1. 6. 3.]
特征向量b
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

求解方程

A = np.mat('1,5; 10,5')    # 构造系数矩阵 A
print(A)   
b = np.mat('4,8').T
print(b)
r=np.linalg.solve(A,b)
print(r)
# 构造转置矩阵 b (这里必须为列向量)
 # 调用 solve 函数求解
[[ 1  5]
 [10  5]]
[[4]
 [8]]
[[0.44444444]
 [0.71111111]]

用sympy包求解方程

from sympy import *
x = Symbol('x')
y = Symbol('y')
print(solve([10 * x - 3*y - 3, 3 * x + 4*y ],[x, y]))
{x: 12/49, y: -9/49}
x = Symbol('x')
solved_value=solve([x**2-100], [x])
print(solved_value)
[(-10,), (10,)]
# 复数解
solved_value = solve([x ** 2 + 9], [x])
print(solved_value)
solved_value = solve([x ** 4 - 9], [x])
print(solved_value)
[(-3*I,), (3*I,)]
[(-sqrt(3),), (sqrt(3),), (-sqrt(3)*I,), (sqrt(3)*I,)]
#cos(x)-1=0
solved_value = solve([cos(x) - 0.5], [x])
print(solved_value)
solved_value = solve([cos(x) - 1], [x])
print(solved_value)
[(1.04719755119660,), (5.23598775598299,)]
[(0,), (2*pi,)]
# 二元二次方程组 x**3+6*x*y=0
#                3*x*y-2*x**2+3=0
x = Symbol('x')
y=  Symbol('y')
solved_value=solve([x**2+6*x*y,3*x*y-2*x**2+3], [x,y])
print(solved_value)
[(-sqrt(30)/5, sqrt(30)/30), (sqrt(30)/5, -sqrt(30)/30)]

你可能感兴趣的:(python,线性代数)