如何使抛物线适合点集? [英] How to fit a parabola to set of points?

查看:103
本文介绍了如何使抛物线适合点集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组要点,如下图所示.所有点的位置都是已知的.我如何才能将抛物线拟合到这组点上,并在抛物线方程(x, y)上获得新的位置?

I have a set of points as seen in the following picture. All points position are known. How can I fit a parabola to this set of points and get the new position on parabolic equation (x, y)?

推荐答案

要实现二次曲线拟合不是一件容易的事(请检查最后的第二个链接).首先,您可以使用简单线性回归,一旦您了解了(最后检查第一个链接)的原理,就可以将其应用于您的情况.

To implement a Quadratic Curve Fitting is not a simple task (check the second link at the end). As a start you could use simple linear regression, once you've understood the principles (check first link at the end) you can apply it for your case.

下面的代码是一个简单的实现,可以将您的数据(x, y)调整为:y = m*x + b:

The code below is a simple implementation that will fit your data (x, y) to: 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;
}

此处有关最小二乘回归二次曲线拟合.

这篇关于如何使抛物线适合点集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆