Fork自 inscode / Python
from sympy import * import numpy as np def OLS(A,b): output='' x1, x2= symbols('x1, x2') A=np.array(A) b=np.array(b) F=0*x1 for i in range(np.shape(A)[0]): F=F+(A[i][0]*x1+A[i][1]*x2-b[i])**2 output+=f'令F(x)={F},\n则原问题化为minF(x)(x∈R)\n记A={A},x=[x1,x2]^T,b={b},\n则F(x)=(Ax-b)^T(Ax-b)。\n' output+=f'{A.T}' ATA=np.dot(A.T,A) ATb=np.dot(A.T,b) x=np.dot(np.linalg.inv(ATA),ATb) output+=f'∴A^TA:\n{ATA}\n A^Tb:\n{ATb}\n (A^TA)^-1:\n{np.linalg.inv(ATA)}\n∴近似解x=(A^TA)^-1 * A^Tb={x}^T' return output if __name__ == '__main__': #等式左边的系数 A=[[1,2], [3,-1], [2,-3]] #等式右边的常数 b=[5, 3, 0] output=OLS(A,b) print(output)