Python写雅可比迭代法
时间: 2023-05-20 08:07:25 浏览: 145
Python实现雅可比迭代法的代码如下:
```python
import numpy as np
def jacobi(A, b, x0, tol=1e-6, max_iter=10000):
"""
Jacobi iteration method for solving linear equation Ax=b,
where A is a matrix, b is a vector, and x0 is the initial guess.
Parameters
----------
A : numpy.ndarray
Coefficient matrix.
b : numpy.ndarray
Constant vector.
x0 : numpy.ndarray
Initial guess.
tol : float, optional
Tolerance for stopping criterion. The default is 1e-6.
max_iter : int, optional
Maximum number of iterations to perform. The default is 10000.
Returns
-------
x : numpy.ndarray
Solution vector.
"""
D = np.diag(np.diag(A))
L = -np.tril(A, k=-1)
U = -np.triu(A, k=1)
M = D
N = L + U
x = x0
for i in range(max_iter):
x_new = np.dot(np.linalg.inv(M), b - np.dot(N, x))
if np.linalg.norm(x_new - x) < tol:
return x_new
x = x_new
return x
```
其中,A是系数矩阵,b是常数向量,x0是初值,tol是容差,max_iter是最大迭代次数。函数返回解向量x。
阅读全文