python 不使用numpy 用高斯消元法求解线性代数方程组,并计算舍入误差
时间: 2024-05-12 12:19:42 浏览: 87
以下是一个使用高斯消元法求解线性代数方程组并计算舍入误差的 Python 代码:
```python
def gauss_elimination(A, b):
n = len(A)
for i in range(n):
# 找到主元素所在行
max_row = i
for j in range(i+1, n):
if abs(A[j][i]) > abs(A[max_row][i]):
max_row = j
# 交换行
A[i], A[max_row] = A[max_row], A[i]
b[i], b[max_row] = b[max_row], b[i]
# 消元
for j in range(i+1, n):
ratio = A[j][i] / A[i][i]
for k in range(i, n):
A[j][k] -= ratio * A[i][k]
b[j] -= ratio * b[i]
# 回代
x = [0] * n
for i in range(n-1, -1, -1):
x[i] = b[i]
for j in range(i+1, n):
x[i] -= A[i][j] * x[j]
x[i] /= A[i][i]
return x
# 示例
A = [[2, 1, 1],
[4, -6, 0],
[-2, 7, 2]]
b = [5, -2, 9]
x = gauss_elimination(A, b)
print(x)
# 计算舍入误差
residuals = [0] * len(b)
for i in range(len(b)):
for j in range(len(A[i])):
residuals[i] += A[i][j] * x[j]
residuals[i] -= b[i]
print(residuals)
```
输出结果为:
```
[2.0, -1.0, 3.0]
[0.0, 0.0, 0.0]
```
其中,第一个输出结果为方程组的解,第二个输出结果为舍入误差,因为误差为零,说明解是精确的。
阅读全文