1. 该多项式基于Eigen库进行求解
2. 根据原始数据进行多项式拟合
Eigen::VectorXd polyfit(Eigen::VectorXd xvals, Eigen::VectorXd yvals, int order)
{
assert(xvals.size() == yvals.size());
assert(order >= 1 && order <= xvals.size() - 1);
Eigen::MatrixXd A(xvals.size(), order + 1);
for (int i = 0; i < xvals.size(); i++)
{
A(i, 0) = 1.0;
}
for (int j = 0; j < xvals.size(); j++)
{
for (int i = 0; i < order; i++)
{
A(j, i + 1) = A(j, i) * xvals(j);
}
}
auto Q = A.householderQr();
auto result = Q.solve(yvals);
return result;
}
3. 根据拟合出的函数方程系数,测试数据
double polyeval(Eigen::VectorXd coeffs, double x)
{
double result = 0.0;
for (int i = 0; i < coeffs.size(); i++)
{
result += coeffs[i] * pow(x, i);
}
return result;
}
4. 示例
#include <Eigen/Eigen>
#include <vector>
int data_size = 100;
int fitting_frequency = 5;//多项式拟合的次数
double x[data_size];
double y[data_size];
for(size_t i = 0; i < origin_data.size(); i++){
x[i] = origin_data[i].x;
y[i] = origin_data[i].y;
}
double *p_x = &x[0];
double *p_y = &y[0];
Eigen::Map<Eigen::VectorXd> px_vals(p_x, data_size);
Eigen::Map<Eigen::VectorXd> py_vals(p_y, data_size);
//多项式拟合,coeffs为拟合函数系数
Eigen::VectorXd coeffs = polyfit(px_vals, py_vals, fitting_frequency);
// 拟合函数,拟合出新的数据
std::vector<double> fitting_y;
for(size_t i = 0; i < origin_data.size(); i++){
double f_y = polyeval(coeffs, origin_data[i].x);
fitting_y.push_back(f_y);
}
//则fitting_y是用拟合函数拟合出的y,可以画图与origin原始y进行对比