曲线拟合的最小二乘法:正交二乘法 python

曲线拟合的最小二乘法:正交二乘法 python

import sympy
x=[]
y=[]
W=[]
a=[]
aa=[]
beita=[]
n=int(input("请输入最高项的次数:"))
xxx=(input("请输入x的值,以空格分隔:"))
yyy=(input("请输入y的值,以空格分隔:"))
'''www=(input("请输入w的值,以空格分隔:"))'''
x=xxx.split(" ")
m=len(x)
y=yyy.split(" ")
'''W=www.split(" ")'''
x=[float(x) for x in x]
y=[float(x) for x in y]
W=[float(x) for x in W]
FAI=[]
he=0
He=0
for i in range(n):
	a.append(0)
for i in range(n+1):
	aa.append(0)
for i in range(m):
	he+=x[i]
	He+=y[i]
a[0]=round(he/6,2)
aa[0]=round(He/6,3)
for i in range(n+1):
	FAI.append(0)
for i in range(n-1):
	beita.append(0)
X=sympy.symbols("x")
Z1=X-a[0]
FAI[1]=Z1
FAI[0]=1
for i in range(2,n+1):
    he0=0
    he1=0
    he2=0
    he3=0
    for j in range(m):
        
        he0+=round(x[j]*round((sympy.sympify(FAI[i-1]).subs(X,x[j])**2),4),3)
        he1+=(sympy.sympify(FAI[i-1]).subs(X,x[j])**2)
        he2+=((sympy.sympify(FAI[i-1]).subs(X,x[j]))**2)
        he3+=((sympy.sympify(FAI[i-2]).subs(X,x[j]))**2)
    a[i-1]=round(round(he0,3)/round(he1,3),4)
    beita[i-2]=round(he2/he3,4)
    FAI[i]=sympy.sympify((X-a[i-1])*(FAI[i-1])-beita[i-2]*FAI[i-2])  
FAI[2]=sympy.expand(FAI[2],X)
for i in range(n):
	
	he0=0
	he1=0
	for j in range(m):
		he0+=y[j]*(sympy.sympify(FAI[i+1]).subs(X,x[j]))
		he1+=sympy.sympify(FAI[i+1]).subs(X,x[j])**2
	aa[i+1]=round(round(he0,4)/round(he1,4),3)
ZZ=0	
for i in range(n+1):	
	ZZ+=aa[i]*FAI[i]
x=sympy.symbols("x")
Z0=sympy.expand(ZZ,X)
print('y=',sympy.collect(Z0,x))

输入案例
曲线拟合的最小二乘法:正交二乘法 python_第1张图片

你可能感兴趣的:(计算方法,python,最小二乘法,开发语言)