【发布时间】:2022-01-16 06:52:51
【问题描述】:
我正在尝试求解以下线性方程组:
10x1+ 40x2+ 70x3= 300
20x1+ 50x2+ 80x3= 360
30x1+ 60x2+ 80x3= 390
通过使用 Cramer 的方法从头实现一个函数:
def cramer(mat, constant): # takes the matrix and the costants
D = np.linalg.det(mat) # calculating the determinant of the original matrix
# substitution of the column with costant and creating new matrix
mat1 = np.array([constant, mat[1], mat[2]])
mat2 = np.array([mat[0], constant, mat[2]])
mat3 = np.array([mat[0], mat[1], constant])
#calculatin determinant of the matrix
D1 = np.linalg.det(mat1)
D2 = np.linalg.det(mat2)
D3 = np.linalg.det(mat3)
#finding the X1, X2, X3
X1 = D1/D
X2 = D2/D
X3 = D3/D
print(X1, X2, X3)
通过在系统上使用上述功能
a = np.array([[10, 40, 70],
[20, 50, 80],
[30, 60, 80]])
b = np.array([300, 360, 390])
我得到以下结果:
cramer(a,b)
-22.99999999999996 21.999999999999964 2.999999999999993
我已经使用 numpy 函数 np.linalg.solve 解决了系统问题,我得到了另一个结果:
x = np.linalg.solve(a, b)
[1. 2. 3.]
我无法在我写过的函数中发现公式错误。我应该在功能中进行哪些调整才能使其正常工作?
【问题讨论】:
标签: python numpy matrix linear-algebra linear-equation