用 C++ 表示給定點集的最佳直線


討論如何用最佳直線表示點集。給定點集的一組值 (x,y),我們需要找到最佳直線 y = mx + c,所以我們只需要找到 m 和 c 的值,例如

Input: no_of_points = 4
x1 = 2, y1 = 3,
x2 = 5, y2 = 6,
x3 = 1, y3 = 3,
x4 = 4, y4 = 5.

Output: m = 0.8, c = 1.85
Explanation: If we apply the value of m and c in the equation y = mx + c for any point (xi, yi) it would give the best straight line covering all the points.
Putting value of m and c in (x2,y2),
L.H.S : mx + c = 0.8 * 5 + 1.85 = 5.85
R.H.S : y = 6 which is nearly equal to L.H.S.

Input: no_of_points = 3
x1 = 3, y1 = 6,
x2 = 2, y2 = 4,
x3 = 1, y3 = 3,

Output: m = 1.5,c = 1.33

解決方法

要解決這個問題,我們需要找到 m 和 c 的值。當點數為 2 時,將有一個唯一的解,但當點數大於 2 時,解可能存在也可能不存在。

假設點數為 n,

那麼我們將有 n 個方程,fn = mxn + c

為了使該方程成為最佳擬合,我們需要找到 fi 的值,使其等於或接近 yi。

設 Z = ( fi - yi )2;現在,我們需要使所有點的該值最小。我們將 ( fi - yi ) 項平方以消除負項。

為了使 Z 最小,它必須滿足:

𝜹(Z) / 𝜹(m) = 0 和 𝜹(Z) / 𝜹(c) = 0。

求解這些方程,

sigma(y) = m * sigma(x) + 點數 * c,以及

sigma(xy) = m * sigma(x2) + c * sigma(x)。

即,

m = (點數 * sigma(xy) - sigma(x) 8 sigma(y) ) / (n * sigma(x2) - sigma(x2) ),以及

c = ( sigma(y) - m * sigma(x) ) / 點數。

因此,現在我們有了直接的公式來找到最終方程的 m 和 c。

示例

上述方法的 C++ 程式碼

#include <cmath>
#include <iostream>
using namespace std;
int main(){
   int X[] = { 3, 2, 1 };
   int Y[] = { 6, 4, 3};
   int no_of_points = sizeof(X) / sizeof(X[0]);
   float m, c;
   int sum_of_X = 0, sum_of_X2 = 0, sum_of_Y = 0, sum_of_XY = 0;
   // calculating all the terms of the equation.
   for (int i = 0; i < no_of_points; i++) {
      sum_of_X = sum_of_X + X[i];
      sum_of_X2 = sum_of_X2 + pow(X[i],2);
      sum_of_Y = sum_of_Y + Y[i];
      sum_of_XY = sum_of_XY + (X[i] * Y[i]);
   }
   // calculating value of m and c using formula.
   m = (no_of_points * sum_of_XY - sum_of_X * sum_of_Y) / (no_of_points * sum_of_X2 - pow(sum_of_X,2));
   c = (sum_of_Y - m * sum_of_X) / no_of_points;
   cout << "m = " << m;
   cout << "\nc = " << c;
   return 0;
}

輸出

m = 1.5
c = 1.33333

結論

在本教程中,我們討論瞭如何找到最佳擬合直線來表示給定的點集。我們討論了一種簡單的方法,首先推匯出 m 和 c 的公式,然後簡單地應用它。我們還討論了這個問題的 C++ 程式,我們可以使用 C、Java、Python 等程式語言來實現。希望本教程對您有所幫助。

更新於:2021 年 11 月 26 日

370 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告