最小二乘法(least squares analysis)是一种 数学 优化 技术,它通过 最小化 误差 的平方和找到一组数据的最佳 函数 匹配。 最小二乘法是用最简的方法求得一些绝对不可知的真值,而令误差平方之和为最小。 最小二乘法通常用于 曲线拟合 (least squares fitting) 。这里有 拟合圆曲线 的公式推导过程 和 vc实现。
VC实现的代码:
1 void CViewActionImageTool::LeastSquaresFitting()
2 {
3 if (m_nNum<3)
4 {
5 return;
6 }
7
8 int i=0;
9
10 double X1=0;
11 double Y1=0;
12 double X2=0;
13 double Y2=0;
14 double X3=0;
15 double Y3=0;
16 double X1Y1=0;
17 double X1Y2=0;
18 double X2Y1=0;
19
20 for (i=0;i<m_nNum;i++)
21 {
22 X1 = X1 + m_points[i].x;
23 Y1 = Y1 + m_points[i].y;
24 X2 = X2 + m_points[i].x*m_points[i].x;
25 Y2 = Y2 + m_points[i].y*m_points[i].y;
26 X3 = X3 + m_points[i].x*m_points[i].x*m_points[i].x;
27 Y3 = Y3 + m_points[i].y*m_points[i].y*m_points[i].y;
28 X1Y1 = X1Y1 + m_points[i].x*m_points[i].y;
29 X1Y2 = X1Y2 + m_points[i].x*m_points[i].y*m_points[i].y;
30 X2Y1 = X2Y1 + m_points[i].x*m_points[i].x*m_points[i].y;
31 }
32
33 double C,D,E,G,H,N;
34 double a,b,c;
35 N = m_nNum;
36 C = N*X2 - X1*X1;
37 D = N*X1Y1 - X1*Y1;
38 E = N*X3 + N*X1Y2 - (X2+Y2)*X1;
39 G = N*Y2 - Y1*Y1;
40 H = N*X2Y1 + N*Y3 - (X2+Y2)*Y1;
41 a = (H*D-E*G)/(C*G-D*D);
42 b = (H*C-E*D)/(D*D-G*C);
43 c = -(a*X1 + b*Y1 + X2 + Y2)/N;
44
45 double A,B,R;
46 A = a/(-2);
47 B = b/(-2);
48 R = sqrt(a*a+b*b-4*c)/2;
49
50 m_fCenterX = A;
51 m_fCenterY = B;
52 m_fRadius = R;
53
54 return;
55 }