多项式拟合

给定自变量数据如下:

0,0.3,0.6,0.9,1.2,1.5,1.8,2.1,2.4,2.7,3

因变量数据如下:

2,2.378,3.944,7.346,13.232,22.25,35.048,52.274,74.576,102.602,137

以及待拟合公式:

\[ y = \sum_{i=1}^{4}p_{i}x^{i-1} \]

polyfit

local print = require('package.print'). print
local plt = require('package.plot')
local mol = libminoptlab

local xdat = mol.matrix.new({0, 0.3000 , 0.6000 , 0.9000 , 1.2000 , 1.5000 , 1.8000 , 2.1000 ,2.4000 , 2.7000 , 3.0000})
local ydat = {2.0000 , 2.3780 , 3.9440 , 7.3460 , 13.2320 , 22.2500 , 35.0480 , 52.2740 ,74.5760 , 102.6020 , 137.0000}


local model = mol.polyfitfun(4)
local p,corr,fval = mol.polyfit(xdat,ydat,model,4)

print({
	p = p,
	corr = corr,
	fval = fval
})


local fit =  mol.tofit(model,p)
local fity = xdat:apply(fit)

local img1 = plt.scatter({{xdat:tovector(),ydat}},{'dat'},{{marker = '*',color='b'}})
local img2 = plt.line({{xdat:tovector(),fity}},{'fit'},{{color = 'r'}})

local fw = plt.framework(111,'多项式拟合',{'x','y'})
plt.show({{fw,{img1,img2}}})

其解是\(p = [ 2,2.3993848369733e-14,3,4 ]^{T}\),相关系数是\(1\),残差平方和是\(1.1945819295375e-27\)。