直线拟合

时间:2024-03-13 20:45:30
  • 拟合直线为:y = a1 * x + a0 (a1、a0为待定参数)
  • 计算公式为:

  • 代码:
     1 //注意:点多的话会溢出,导致m_lineAscent、m_lineOffset失效
    2 void CLineFittingDlg::CalcAscentOffset(void)
    3 {
    4 if (!m_OrgPtArray.empty())
    5 {
    6 int X = 0;//x1+...xm
    7 int Y = 0;//y1+...ym
    8 int XY = 0;//x1*y1+...xm*ym
    9 int X2 = 0;//x1*x1+...xm*xm
    10 int n = m_OrgPtArray.size();
    11
    12 for (int i=0;i<n;i++)
    13 {
    14 X += m_OrgPtArray[i].x;
    15 Y += m_OrgPtArray[i].y;
    16 XY += m_OrgPtArray[i].x * m_OrgPtArray[i].y;
    17 X2 += m_OrgPtArray[i].x * m_OrgPtArray[i].x;
    18 }
    19
    20 if (n*X2 - X*X == 0)//垂直方向
    21 {
    22 m_lineAscent = MAX_ASCENT;
    23 m_lineOffset = X / n;
    24 }
    25 else
    26 {
    27 m_lineAscent = (double)(n*XY - X*Y) / (n*X2 - X*X);
    28 m_lineOffset = (double)(Y*X2 - XY*X) / (n*X2 - X*X);
    29 }
    30
    31 }
    32 }
  • 结果(蓝色为原始曲线,红色为拟合直线):