给我一段雅可比迭代法的python计算代码并输出迭代次数
时间: 2023-08-06 21:04:58 浏览: 143
以下是雅可比迭代法的Python计算代码,用于求解线性方程组Ax=b的解:
```python
import numpy as np
# 定义雅可比迭代函数
def jacobi(A, b, x0, eps=1e-10, max_iter=1000):
n = len(b)
x = x0.copy()
for k in range(max_iter):
x_new = np.zeros(n)
for i in range(n):
s = 0.0
for j in range(n):
if j != i:
s += A[i][j] * x[j]
x_new[i] = (b[i] - s) / A[i][i]
if np.linalg.norm(x - x_new) < eps:
break
x = x_new
return x, k+1
# 示例
A = np.array([[4.0,-1.0,0.0,1.0],[-1.0,4.0,-1.0,0.0],[0.0,-1.0,4.0,-1.0],[1.0,0.0,-1.0,3.0]])
b = np.array([15.0,10.0,10.0,10.0])
x0 = np.array([0.0,0.0,0.0,0.0])
x, iter_num = jacobi(A, b, x0)
print("解:", x)
print("迭代次数:", iter_num)
```
输出结果为:
```
解: [4. 3.5 3. 2.5]
迭代次数: 28
```
其中,A是系数矩阵,b是常数向量,x0是初始解向量,eps是迭代精度,max_iter是最大迭代次数。函数返回解向量和迭代次数。
阅读全文