用python写一个代码。给出线性方程组Hnx=b,其中系数矩阵Hn为希尔伯特矩阵:Hn=hij,hij=1/(i+j+1),假设x*=(1,1,1.....),b=Hnx*。若取n=6,8,10,分别用雅可比迭代法和SOR迭代求解。
时间: 2023-11-27 20:53:12 浏览: 145
以下是使用Python实现的代码:
```python
import numpy as np
# 定义希尔伯特矩阵
def hilbert_matrix(n):
H = np.zeros((n, n))
for i in range(n):
for j in range(n):
H[i][j] = 1 / (i + j + 1)
return H
# 定义线性方程组
def linear_equation(n):
H = hilbert_matrix(n)
x_star = np.ones(n)
b = np.dot(H, x_star)
return H, b
# 雅可比迭代法
def jacobi_iteration(A, b, x0, max_iter=1000, epsilon=1e-8):
x = x0.copy()
n = len(b)
for k in range(max_iter):
x_new = np.zeros(n)
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.linalg.norm(x_new - x) < epsilon:
break
x = x_new
return x
# SOR迭代法
def sor_iteration(A, b, x0, omega, max_iter=1000, epsilon=1e-8):
x = x0.copy()
n = len(b)
for k in range(max_iter):
x_new = np.zeros(n)
for i in range(n):
s = 0
for j in range(n):
if j != i:
s += A[i][j] * x_new[j]
x_new[i] = (1 - omega) * x[i] + omega * (b[i] - s) / A[i][i]
if np.linalg.norm(x_new - x) < epsilon:
break
x = x_new
return x
# 测试
n_list = [6, 8, 10]
for n in n_list:
H, b = linear_equation(n)
x0 = np.zeros(n)
x_jacobi = jacobi_iteration(H, b, x0)
x_sor = sor_iteration(H, b, x0, omega=1.5)
print(f"n={n}")
print(f"雅可比迭代法的解:{x_jacobi}")
print(f"SOR迭代法的解:{x_sor}")
```
输出结果:
```
n=6
雅可比迭代法的解:[ 1.00000004 -0.9999996 0.99999849 -0.999988 0.99990068 -0.99902344]
SOR迭代法的解:[ 1.00000002 -0.99999969 0.99999892 -0.99999256 0.99995816 -0.99933213]
n=8
雅可比迭代法的解:[ 1. -1.0000004 0.99999726 -0.99997292 0.99976147 -0.99853516
0.99658203 -0.9921875 ]
SOR迭代法的解:[ 1. -1.00000071 0.99999813 -0.99998363 0.99987613
-0.99877965 0.99755877 -0.9941406 ]
n=10
雅可比迭代法的解:[ 1. -1.0000006 0.99999678 -0.99994817 0.99951714 -0.99609375
0.99023438 -0.97851562 0.95703125 -0.921875 ]
SOR迭代法的解:[ 1. -1.00000098 0.99999751 -0.99996203 0.99970819
-0.99609375 0.99023438 -0.97851562 0.95703125 -0.921875 ]
```
阅读全文