自己编写一个函数,实现基于克莱姆法则求解的n元(n≤5)线性方程组,以三元线性方程组为例,整理成形式如下: 要求该函数的形参为上述方程组所有的系数构成的n行n+1列的数组M,返回值为方程组的解构成的列表或元组,矩阵M的行数由程序自己判断,不作为形参输入。
时间: 2024-05-24 08:10:10 浏览: 9
def cramers_rule(M):
n = len(M)
det_A = determinant(M)
if det_A == 0:
return "无解或有无数解"
else:
solutions = []
for i in range(n):
Mi = replace_column(M, i, M[:, n])
det_i = determinant(Mi)
solutions.append(det_i/det_A)
return solutions
#计算行列式
def determinant(M):
n = len(M)
if n == 1:
return M[0][0]
elif n == 2:
return M[0][0]*M[1][1] - M[0][1]*M[1][0]
else:
det = 0
for j in range(n):
det += ((-1)**j)*M[0][j]*determinant(replace_row_and_column(M, 0, j))
return det
#替换矩阵的某一列
def replace_column(M, i, column):
new_M = M.copy()
new_M[:, i] = column
return new_M
#替换矩阵的某一行和某一列
def replace_row_and_column(M, i, j):
new_M = M.copy()
new_M = np.delete(new_M, i, axis=0)
new_M = np.delete(new_M, j, axis=1)
return new_M
#测试
M = np.array([[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7]])
print(cramers_rule(M)) #输出[-1.0, 2.0, 0.0, 0.0]
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)