我正在做一个算法,我给出了x和y解决方案,我需要找到该解决方案的二次公式。 我的意思是: 如果我给出了输出:
f(1) = 1
f(2) = 5
f(3) = 13
f(4) = 25
所以,函数应该返回1,5,13,25
给出该输出的函数是:2x ^ 2-2x + 1,但我该如何得到它?
答案 0 :(得分:1)
如果你的y值是精确的,你可以求解线性方程组
a*x1^2 + b*x1 + c = y1
a*x2^2 + b*x2 + c = y2
a*x3^2 + b*x3 + c = y3
将已知值替换为三个点并找到未知系数a,b,c
如果值是近似值,请使用least squares方法(更精确 - 多项式最小二乘)和所有点
答案 1 :(得分:0)
这是至少sqaure分析的代码。它是为newmat矩阵库编写的。因为我现在不使用它所以我懒得把它改写成我目前正在使用的犰狳库。为了避免错误,newmat以1而不是0的向量/矩阵索引开始。
void polynomial_approx( const vector<double>& x, const vector<double>& fx, vector<double>& coeff, int pd)
{
// x - input values of independent variable
// fx - input values of dependent variable
// coeff - output vector with polynomial coeffiecients
// pd - polynomial degree
if ( x.size() < pd ){
cerr << "Not enough data for such high polynomial degree." << endl;
};
coeff.clear();
Matrix A(x.size(), pd + 1);
Matrix D(pd+1,pd+1);
ColumnVector y(fx.size());
ColumnVector dx;
// converting vector from c++ type to newmat vector
for (unsigned int i = 0; i < fx.size(); i++)
y(i+1) = fx[i];
// creating the design matrix
for (unsigned int i = 1; i <= x.size();i++ ){
for (unsigned int j = 1; j<= pd+1;j++ ){
A(i,j) = pow(x[i],j-1);
}
}
// compute the unknown coefficients
dx = (A.t() * A ).i() * A.t() * y;
for (unsigned int i = 1; i<= dx.Ncols(); i++)
coeff.push_back( dx(i) );
/* reconstruction of polynomial */
vector<double> recon (x.size(), 0.0 );
for ( unsigned int i = 0; i < x.size() ; i++){
for ( unsigned int j = 0; j< coeff.size(); j++){
recon[i] += coeff[j]*pow( x[i], (double) j );
}
}
}