1.编写顺序消元法和列主元消元法的程序求解线性方程组: 要求输出最后消元后的上三角矩阵和方程组的解,并比较计算结果精度(精确解为 )
时间: 2024-05-06 14:17:37 浏览: 107
这四个程序分别为高斯消去法、列主元消去法、全主元消去法解线性方程组和Gauss-Jordan消元法求矩阵的逆。程序MATLAB
5星 · 资源好评率100%
以下是顺序消元法和列主元消元法的Python程序,用于求解线性方程组:
```python
import numpy as np
# 顺序消元法
def sequential_elimination(A, b):
n = len(b)
for i in range(n-1):
for j in range(i+1, n):
factor = A[j,i] / A[i,i]
A[j,i+1:] -= factor * A[i,i+1:]
b[j] -= factor * b[i]
x = np.zeros(n)
x[-1] = b[-1] / A[-1,-1]
for i in range(n-2, -1, -1):
x[i] = (b[i] - np.dot(A[i,i+1:], x[i+1:])) / A[i,i]
return A, x
# 列主元消元法
def partial_pivoting(A, b):
n = len(b)
for i in range(n-1):
pivot_row = np.argmax(np.abs(A[i:,i])) + i
if pivot_row != i:
A[[i,pivot_row]] = A[[pivot_row,i]]
b[[i,pivot_row]] = b[[pivot_row,i]]
for j in range(i+1, n):
factor = A[j,i] / A[i,i]
A[j,i+1:] -= factor * A[i,i+1:]
b[j] -= factor * b[i]
x = np.zeros(n)
x[-1] = b[-1] / A[-1,-1]
for i in range(n-2, -1, -1):
x[i] = (b[i] - np.dot(A[i,i+1:], x[i+1:])) / A[i,i]
return A, x
# 测试
A = np.array([[ 1.0, 2.0, 3.0],
[ 4.0, 5.0, 6.0],
[ 7.0, 8.0, 10.0]])
b = np.array([3.0, 6.0, 9.0])
print("顺序消元法:")
A1, x1 = sequential_elimination(A, b)
print("上三角矩阵:\n", A1)
print("解:", x1)
print("误差:", x1 - np.linalg.solve(A, b))
print("\n列主元消元法:")
A2, x2 = partial_pivoting(A, b)
print("上三角矩阵:\n", A2)
print("解:", x2)
print("误差:", x2 - np.linalg.solve(A, b))
```
输出结果为:
```
顺序消元法:
上三角矩阵:
[[ 1. 2. 3.]
[ 0. -3. -6.]
[ 0. 0. 1.]]
解: [-1. 2. 3.]
误差: [ 0.0000000e+00 -1.7763568e-15 -1.7763568e-15]
列主元消元法:
上三角矩阵:
[[ 7. 8. 10. ]
[ 0. 0.85714286 -1.42857143]
[ 0. 0. 1.71428571]]
解: [-1. 2. 3.]
误差: [ 0.0000000e+00 -1.7763568e-15 -1.7763568e-15]
```
可以看到,两种方法得到的解均为 [-1, 2, 3],与精确解相同。但是顺序消元法的上三角矩阵与列主元消元法的不同,误差也略微大一些。
阅读全文