先放代码,有时间补内容
import numpy as ny
import sympy as sy
from guass_swap import gaussin
ny.set_printoptions(suppress=True)
def LeastSquares(X,Y,m):
assert len(X)==len(Y)
n=len(X)
A = ny.zeros([m,m])
B = ny.transpose(ny.zeros([m]))
for i in range(m):
for j in range(m):
for k in range(n):
A[i][j]=A[i][j]+X[k]**(i+j)
A[0][0]=n
for i in range(m):
for k in range(n):
B[i]=B[i]+Y[k]*X[k]**(i)
print(A)
print(B)
a = gaussin(A, B)
x = sy.symbols("x")
ans=0
for i in range(m):
ans = ans + a[i] * x**(i)
print( ans )
if __name__ == '__main__': #当模块被直接运行时,以下代码块将被运行,当模块是被导入时,代码块不被运行。
m=3
X=[1,3,4,5,6,7,8,9,10]
Y=[10,5,4,2,1,1,2,3,4]
LeastSquares(X,Y,m)