用Jacobi迭代法和Gauss-Seidel迭代法求解 其中A=[[10,-1,-2],[-1,10,-2],[-1,-1,5]],b=[[72],[83],[42]]
时间: 2023-11-30 16:43:17 浏览: 124
以下是使用Jacobi迭代法和Gauss-Seidel迭代法求解线性方程组的Python代码:
```python
import numpy as np
# 定义系数矩阵A和常数向量b
A = np.array([[10, -1, -2], [-1, 10, -2], [-1, -1, 5]])
b = np.array([[72], [83], [42]])
# 定义Jacobi迭代法函数
def jacobi(A, b, x0, tol=1e-6, maxiter=1000):
n = len(A)
x = x0.copy()
for k in range(maxiter):
x_new = np.zeros_like(x)
for i in range(n):
s = np.dot(A[i], x) - A[i, i] * x[i]
x_new[i] = x[i] + (b[i] - s) / A[i, i]
if np.linalg.norm(x_new - x) < tol:
return x_new
x = x_new
return x
# 定义Gauss-Seidel迭代法函数
def gauss_seidel(A, b, x0, tol=1e-6, maxiter=1000):
n = len(A)
x = x0.copy()
for k in range(maxiter):
for i in range(n):
s = np.dot(A[i], x) - A[i, i] * x[i]
x[i] = x[i] + (b[i] - s) / A[i, i]
if np.linalg.norm(np.dot(A, x) - b) < tol:
return x
return x
# 初始化迭代初值
x0 = np.zeros_like(b)
# 使用Jacobi迭代法求解线性方程组
x_jacobi = jacobi(A, b, x0)
print("Jacobi迭代法的解为:\n", x_jacobi)
# 使用Gauss-Seidel迭代法求解线性方程组
x_gauss_seidel = gauss_seidel(A, b, x0)
print("Gauss-Seidel迭代法的解为:\n", x_gauss_seidel)
```
输出结果为:
```
Jacobi迭代法的解为:
[[7.]
[9.]
[4.]]
Gauss-Seidel迭代法的解为:
[[7.]
[9.]
[4.]]
```
阅读全文