用python写雅可比迭代法的代码
时间: 2023-05-24 16:05:02 浏览: 283
以下是使用Python实现雅可比迭代法的代码示例:
```python
import numpy as np
def jacobi_iteration(A, b, max_iterations=100, tolerance=1e-7):
"""
使用雅可比迭代法求解Ax = b的线性方程组
Args:
A (ndarray): n x n的系数矩阵
b (ndarray): n个常数值的向量
max_iterations (int, optional): 迭代的最大次数. Defaults to 100.
tolerance (float, optional): 迭代停止的绝对误差. Defaults to 1e-7.
Returns:
x (ndarray): n维向量, 表示Ax = b的解
iterations (int): 迭代次数
"""
n = len(b)
x = np.zeros(n)
x_new = np.zeros(n)
# 记录迭代次数
iterations = 0
# 迭代过程
while iterations < max_iterations:
for i in range(n):
s = 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.abs(x - x_new).max() < tolerance:
return x_new, iterations
# 更新迭代解
x = x_new.copy()
# 迭代次数加1
iterations += 1
# 迭代次数已达到最大值, 返回当前的迭代解和迭代次数
return x_new, iterations
```
使用方法:
```python
A = np.array([[5, 1, 1],
[1, 5, 1],
[1, 1, 5]])
b = np.array([7, 7, 7])
x, iterations = jacobi_iteration(A, b)
print("解:", x)
print("迭代次数:", iterations)
```
阅读全文