本篇文章所讲代码是对2018年全国大学生数学建模比赛A题附件的数据进行拟合,代码如下:
代码语言:javascript复制import xlrd
import numpy
from matplotlib import pyplot as pl
data=xlrd.open_workbook(r'C:UsersadminDesktop1.xlsx')
table=data.sheet_by_name('sheet1')
a=table.col_values()[:]
b=table.col_values()[:]
x=numpy.array(a)
y=numpy.array(b)
class fitting:
def __init__(self,X,Y):
self.x=numpy.array(X)
self.y=numpy.array(Y)
def fitting(self,n):
self.z=numpy.polyfit(self.x,self.y,n)
self.p=numpy.poly1d(self.z)
self.error=numpy.abs(self.y-numpy.polyval(self.p,self.x))
self.ER2=numpy.sum(numpy.power(self.error,))/len(self.x)
return self.z,self.p
def geterror(self):
return self.error,self.ER2
def show(self):
figure1=pl.figure()
pl.plot(self.x,self.y,'ro-',markersize=.,figure=figure1,label='origin data')
pl.plot(self.x,numpy.polyval(self.p,self.x),markersize=,figure=figure1,label='fitting data')
pl.legend()
pl.show()
def predict(self,x):
return numpy.polyval(self.p,x)
F=fitting(x,y)
z,p=F.fitting()
e,E=F.geterror()
print ('系数:',z)
print ('拟合函数:',p)
print ('最小平方误差:',E)
a=#通过改变a的值来进行预测
print ('F({})的预测值'.format(a),F.predict(a))
F.show()