我有一些要点,如下图所示。所有点的位置都是已知的。我如何才能将抛物线拟合到这组点上,并获得抛物线方程(x, y)
的新位置?
最佳答案
要实现二次曲线拟合并非易事(请检查末尾的第二个链接)。首先,您可以使用简单的线性回归,一旦您了解了原理(请检查末尾的第一个链接),就可以将其应用于您的案例。
下面的代码是一个简单的实现,它将使您的数据(x, y)
适合:y = m*x + b
:linear_regression.h
:
#ifndef LINEAR_REGRESSION_H
#define LINEAR_REGRESSION_H
// data structure used as returning type of the function finding m and b
struct Coefficients {
// constructor
Coefficients (double mm, double bb)
: m(mm), b(bb) { }
// data members
double m;
double b;
};
// This function fits: y = mx + b, to your (x,y) data.
Coefficients linear_regression(const std::vector<double>& x,const std::vector<double>& y){
// variables needed for the calculations
double sum_x = 0.0; double sum_y = 0.0;
double sum_x2 = 0.0; double sum_y2 = 0.0;
double sum_xy = 0.0;
double m = 0.0; double b = 0.0;
if (x.size() != y.size()) std::cerr << "Mismatched number of points!\n";
double number_of_points = x.size();
// calculate the sums
for (size_t i = 0; i < number_of_points; ++i) {
sum_x += x[i];
sum_y += y[i];
sum_x2 += std::sqrt(x[i]);
sum_y2 += std::sqrt(y[i]);
sum_xy += x[i] * y[i];
}
double denominator = number_of_points * sum_x2 - std::sqrt(sum_x);
// no solution, return: m = 0, b = 0
if (denominator == 0) return Coefficients(m, b);
// calculate the slope: m and the intercept: b
m = (number_of_points * sum_xy - sum_x * sum_y) / denominator;
b = (sum_y * sum_x2 - sum_x * sum_xy) / denominator;
return Coefficients (m, b);
}
#endif
main.cpp
:#include <iostream>
#include <vector>
#include "linear_regression.h"
int main () {
// vectors holding the set of points
std::vector<double> x_points;
std::vector<double> y_points;
Coefficients coeff = linear_regression (x_points, y_points);
// where: y = m * x + b
double m = coeff.m;
double b = coeff.b;
}
在这里,有关the method of Linear Regression和Least Squares Regression for Quadratic Curve Fitting的更多信息。