[英]How to fit a parabola to set of points?
要實現二次曲線擬合並非易事(請檢查最后的第二個鏈接) 。 首先,您可以使用簡單的線性回歸 ,一旦您了解了原理(最后檢查第一個鏈接) ,就可以將其應用於您的案例。
下面的代碼是一個簡單的實現,可以將您的數據(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;
}
您可以用極坐標表示曲線(請參見Wikipedia:“ 極坐標系統 ”)。 只需在拋物線內部選擇任意點作為原點,並將(x,y)
坐標轉換為(r,phi)
坐標。 現在,您可以將點表示為r = f(phi)
,其中r
是到原點的距離, phi
是極坐標中的角度。 一個總能做為原點的點是所有點的平均值,因為它總是位於拋物線內。
下一步,您需要在新的極坐標中變換拋物線方程。 與簡單的拋物線方程相比,它需要一個額外的參數來旋轉。 該方程式可用於擬合您的數據,例如,使用Wikipedia文章“ 非線性最小二乘法 ”中所述方法的實現。
我不知道這是否是解決此問題的最簡單方法,但我希望它至少可以使您對如何進行操作有所了解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.