2.8 求解下列线性方程组 4x1+x2=1,x1+4x2+x3=2,x2+4x3+x4=3,......,x998+4x999+x1000=999,x999+4x1000=1000
点击查看代码
import numpy as np
# 初始化系数矩阵A和常数项向量b
n = 1000
A = np.zeros((n, n))
b = np.arange(1, n+1)
# 填充系数矩阵A
for i in range(n):
A[i, i] = 4 # 对角线元素为4
if i < n-1:
A[i, i+1] = 1 # 每一行的下一个元素为1
if i > 0:
A[i, i-1] = 1 # 每一行的上一个元素为1(除了第一行)
# 求解线性方程组 Ax = b
x = np.linalg.solve(A, b)
# 打印解
print("解向量 x:")
for i in range(n):
print(f"x{i+1} = {x[i]:.4f}")
print("学号:3004")