高斯消元解线性方程组代码
时间: 2024-09-29 22:01:08 浏览: 34
高斯消元法是一种常见的求解线性方程组的方法,它通过一系列行操作将系数矩阵化简成阶梯形或简化阶梯形,进而找到未知数的解。以下是使用Python语言实现简单高斯消元法的代码示例:
```python
def gauss_elimination(A, b):
n = len(A) # 系统的变量个数
for i in range(n):
# 如果当前列元素为0,则交换当前列与下一个非零列
if A[i][i] == 0:
non_zero_row_index = i + 1
while non_zero_row_index < n and A[non_zero_row_index][i] == 0:
non_zero_row_index += 1
if non_zero_row_index < n:
A[[i, non_zero_row_index]] = A[[non_zero_row_index, i]]
b[[i, non_zero_row_index]] = b[[non_zero_row_index, i]]
# 对当前列进行消元,将所有下标大于i的元素除以A[i][i]
for j in range(i+1, n):
ratio = A[j][i] / A[i][i]
A[j] = [a - ratio * b for a in A[j]]
b[j] -= ratio * b[i]
# 检查是否得到单位矩阵,如果已经全为0,则说明无法解出唯一解或无解
is_invertible = all(abs(val) > 1e-9 for row in A[n:] for val in row)
# 回带求解
x = [0] * n
for i in reversed(range(n)):
x[i] = (b[i] - sum(A[i][j] * x[j] for j in range(i))) / A[i][i]
return is_invertible, x
# 示例用法
A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b = [10, 11, 12]
solution, invertible = gauss_elimination(A, b)
if invertible:
print(f"线性方程组有唯一解:{solution}")
else:
print("线性方程组无解或有无穷多解")
阅读全文