2-7

陈元元發表於2024-10-08

import numpy as np
A = np.array([[4, 2, -1], [3, -1, 2], [11, 3, 0]])
b = np.array([2, 10, 8])
x = np.linalg.solve(A, b)
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)