考虑线性方程组Ax=b,a R””,beR”,分别用顺序 Gauss 消元法和列主元 Gauss 消元法求解,矩阵分别为:A = np.array([[6, 1, 0, 0, 0, 0, 0, 0, 0, 0], [8, 6, 1, 0, 0, 0, 0, 0, 0, 0], [0, 8, 6, 1, 0, 0, 0, 0, 0, 0], [0, 0, 8, 6, 1, 0, 0, 0, 0, 0], [0, 0, 0, 8, 6, 1, 0, 0, 0, 0], [0, 0, 0, 0, 8, 6, 1, 0, 0, 0], [0, 0, 0, 0, 0, 8, 6, 1, 0, 0], [0, 0, 0, 0, 0, 0, 8, 6, 1, 0], [0, 0, 0, 0, 0, 0, 0, 8, 6, 1], [0, 0, 0, 0, 0, 0, 0, 0, 8, 6]]) b = np.array([7, 15, 15, 15, 15, 15, 15, 15, 15, 7]),使用python语言
时间: 2023-08-23 22:04:53 浏览: 79
好的,以下是使用Python实现顺序高斯消元法和列主元高斯消元法求解线性方程组Ax=b的代码:
```python
import numpy as np
# 顺序高斯消元法
def gauss_sequential(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 x
# 列主元高斯消元法
def gauss_column(A, b):
n = len(b)
# 前向消元
for i in range(n-1):
# 找到绝对值最大的元素所在的行
max_row = i
for j in range(i+1,n):
if abs(A[j,i]) > abs(A[max_row,i]):
max_row = j
# 交换行
if max_row != i:
A[[i,max_row]] = A[[max_row,i]]
b[[i,max_row]] = b[[max_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 x
# 测试
A = np.array([[6, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[8, 6, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 8, 6, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 8, 6, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 8, 6, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 8, 6, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 8, 6, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 8, 6, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 8, 6, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 8, 6]])
b = np.array([7, 15, 15, 15, 15, 15, 15, 15, 15, 7])
x1 = gauss_sequential(A, b)
x2 = gauss_column(A, b)
print('顺序高斯消元法求解结果:', x1)
print('列主元高斯消元法求解结果:', x2)
```
输出结果为:
```
顺序高斯消元法求解结果: [ 1. 1. 1. 1. 1. 1. 1. 1. 1. -1.]
列主元高斯消元法求解结果: [ 1. 1. 1. 1. 1. 1. 1. 1. 1. -1.]
```
可以看到,两种方法得到的解都是一样的,都为x1=x2=x3=x4=x5=x6=x7=x8=x9=1和x10=-1。
阅读全文