import numpy as np
生成系数矩阵A
A = np.zeros((1000, 1000))
np.fill_diagonal(A, 4)
np.fill_diagonal(A[:, 1:], 1)
np.fill_diagonal(A[1:, :], 1)
生成常数向量b
b = np.arange(1, 1001)
判断解的情况
if np.linalg.matrix_rank(A) == np.linalg.matrix_rank(np.column_stack((A, b))):
if np.linalg.matrix_rank(A) == A.shape[1]:
print("线性方程组有唯一解")
x_unique = np.linalg.solve(A, b)
print("唯一解 x =", x_unique)
else:
print("线性方程组有无穷多解")
x_least_squares = np.linalg.lstsq(A, b, rcond=None)[0]
print("最小二乘解 x =", x_least_squares)
else:
print("线性方程组无解")
x_least_squares = np.linalg.lstsq(A, b, rcond=None)[0]
print("最小二乘解 x =", x_least_squares)
x_min_norm = np.linalg.pinv(A).dot(b)
print("最小范数解 x =", x_min_norm)