jacobi迭代Python
时间: 2024-10-13 21:01:36 浏览: 21
Jacobi迭代算法的Python实现详解
Jacobi 迭代是一种用于求解线性方程组的数值方法,特别是在矩阵是对角占优的情况下效率较高。在 Python 中,我们可以使用 NumPy 库来实现 Jacobi 迭代算法。以下是基本步骤:
1. **导入所需的库**:
```python
import numpy as np
```
2. **定义方程组的系数矩阵和常数项**:
```python
A = np.array([[4, -1], [-1, 5]])
b = np.array([6, 8])
```
3. **初始化迭代变量**(通常选择矩阵对角线元素作为初始值):
```python
x0 = np.zeros_like(b)
```
4. **编写 Jacobi 迭代函数**:
```python
def jacobi_iteration(A, b, x0, iterations):
n = len(A)
for _ in range(iterations):
x_new = (b - A.diagonal()[:, None] * x0) / A.diagonal()
x0 = x_new
return x_new
```
5. **运行迭代并打印结果**:
```python
iterations = 100
solution = jacobi_iteration(A, b, x0, iterations)
print(f"Solution after {iterations} iterations: \n{x0}")
```
阅读全文