无第三方库Python实现Cramer法则解3x3方程组:索引越界问题求助
解决Cramer法则求解3x3方程组的索引越界与计算错误问题
问题根源
- 索引越界:代码在构建
d1/d2/d3时访问了coeff[x][3],但用户输入的是3x3矩阵(仅包含0/1/2三个列索引)。Cramer法则需要的是增广矩阵——每行格式为[x系数, y系数, z系数, 常数项],也就是3行4列的矩阵,最后一列是方程等号右侧的值。 - 行列式计算错误:原
determinantOfMatrix函数的展开式符号有误,会导致行列式结果错误,进而影响解的计算。
修正方案
1. 修正输入逻辑
强制用户输入3行4列的增广矩阵,固定输入维度(因为是3x3方程组,无需让用户自定义行列数),避免维度不匹配问题。
2. 修正行列式计算函数
按照3x3行列式的标准展开式实现:
$$
\det\begin{pmatrix}
a & b & c \
d & e & f \
g & h & i
\end{pmatrix} = a(ei - fh) - b(di - fg) + c(dh - eg)
$$
3. 添加输入验证
确保用户输入的矩阵维度正确,提前拦截错误输入。
修改后的完整代码
# 计算3x3矩阵的行列式 def determinantOfMatrix(mat): # 标准3x3行列式展开公式 a, b, c = mat[0] d, e, f = mat[1] g, h, i = mat[2] return a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g) # 用Cramer法则求解3x3线性方程组 def findSolution(augmented_mat): # 提取系数矩阵D d = [ [augmented_mat[0][0], augmented_mat[0][1], augmented_mat[0][2]], [augmented_mat[1][0], augmented_mat[1][1], augmented_mat[1][2]], [augmented_mat[2][0], augmented_mat[2][1], augmented_mat[2][2]] ] # 构建D1(替换第一列为常数项) d1 = [ [augmented_mat[0][3], augmented_mat[0][1], augmented_mat[0][2]], [augmented_mat[1][3], augmented_mat[1][1], augmented_mat[1][2]], [augmented_mat[2][3], augmented_mat[2][1], augmented_mat[2][2]] ] # 构建D2(替换第二列为常数项) d2 = [ [augmented_mat[0][0], augmented_mat[0][3], augmented_mat[0][2]], [augmented_mat[1][0], augmented_mat[1][3], augmented_mat[1][2]], [augmented_mat[2][0], augmented_mat[2][3], augmented_mat[2][2]] ] # 构建D3(替换第三列为常数项) d3 = [ [augmented_mat[0][0], augmented_mat[0][1], augmented_mat[0][3]], [augmented_mat[1][0], augmented_mat[1][1], augmented_mat[1][3]], [augmented_mat[2][0], augmented_mat[2][1], augmented_mat[2][3]] ] D = determinantOfMatrix(d) D1 = determinantOfMatrix(d1) D2 = determinantOfMatrix(d2) D3 = determinantOfMatrix(d3) print(f"D = {D}, D1 = {D1}, D2 = {D2}, D3 = {D3}") # 判断解的情况 if D != 0: x = D1 / D y = D2 / D z = D3 / D print(f"唯一解:x = {x}, y = {y}, z = {z}") else: if D1 == 0 and D2 == 0 and D3 == 0: print("方程组有无穷多解") else: print("方程组无解") if __name__ == "__main__": print("请输入3x3线性方程组的增广矩阵(每行输入4个整数,用空格分隔):") augmented_mat = [] for _ in range(3): # 读取每行输入并转为整数列表 row = list(map(int, input(f"第{_+1}行:").split())) # 验证每行元素数量 if len(row) != 4: print("错误:每行必须输入4个元素(3个系数+1个常数项)") exit() augmented_mat.append(row) print("输入的增广矩阵:", augmented_mat) findSolution(augmented_mat)
使用说明
以方程组为例:
2x + y - z = 8 -3x - y + 2z = -11 -2x + y + 2z = -3
输入时每行依次输入:2 1 -1 8、-3 -1 2 -11、-2 1 2 -3,即可得到正确解x=2, y=3, z=-1。
内容的提问来源于stack exchange,提问作者Jherky
相关产品推荐
相关产品推荐

