编制 Jacobi 迭代法、Gauss-Seidel 迭代法和超松弛(SOR)迭代法解方程组 Ax=b 的程序
时间: 2024-10-14 09:10:07 浏览: 61
当然可以,这些迭代法通常用于求解线性系统Ax = b,特别是在数值分析和工程计算中。以下是简单的Python示例,演示如何使用Jacobi、Gauss-Seidel和SOR迭代法:
```python
import numpy as np
def jacobi(A, b, iterations, tolerance=1e-6):
n = A.shape[0]
x = np.zeros(n)
delta = np.inf
for _ in range(iterations):
old_delta = delta
x_new = (b - A.dot(x)) / A.diagonal()
delta = np.max(np.abs(x_new - x))
x = x_new
if delta < tolerance:
break
return x_new
def gauss_seidel(A, b, iterations, tolerance=1e-6):
n = A.shape[0]
x = np.zeros(n)
for _ in range(iterations):
for i in range(n):
if i != 0:
x[i] = (b[i] - np.sum(A[i, :i] * x[:i])) / A[i, i]
else:
x[i] = b[i] / A[i, i]
if abs(x[i]) < tolerance:
break
return x
def sor(A, b, omega, iterations, tolerance=1e-6):
n = A.shape[0]
x = np.zeros(n)
delta = np.inf
for _ in range(iterations):
x_new = (omega * (x + A @ x) + (1 - omega) * b) / (omega * A.diagonal() + (1 - omega))
delta = np.max(np.abs(x_new - x))
x = x_new
if delta < tolerance:
break
return x_new
# 示例用法
A = np.array([[4, -1], [-1, 5]])
b = np.array([7, 9])
iterations = 100
jacobi_sol = jacobi(A, b, iterations)
gauss_seidel_sol = gauss_seidel(A, b, iterations)
sor_sol = sor(A, b, 1.5, iterations)
print(f"Jacobi 方法结果:{jacobi_sol}")
print(f"Gauss-Seidel 方法结果:{gauss_seidel_sol}")
print(f"SOR 方法结果(ω=1.5):{sor_sol}")
阅读全文