1. 程式人生 > >利用C#實現最小二乘法

利用C#實現最小二乘法

最小二乘法可根據座標點的資訊擬合出一條最優直線,y=bx+a,保證每個座標點到直線的距離之和達到最小值。

前提條件是先篩選出有效的座標點,再進行演算法處理。

程式碼如下:(實測可用)

/****************宣告定義*************************/

            float[] distance = new float[271];  

            float length;

            float[] ArrPoint_X = new float[270];
            float[] ArrPoint_Y = new float[270];

            ArrayList pointX = new ArrayList();
            ArrayList pointY = new ArrayList();
            float lengthX;
            float lengthY;
            float theta;
            float dis_length;
            float dis_theta;

/****************函式實現*************************//最小二乘法,擬合直線
            int ArrPoint_Count = 0;
            for (int i = (135 - 23 * 3); i <= (135 + 23 * 3); i++)   //邊緣檢測
            {
                length = distance[i];
                if ((length > 100) && (length < User_length))
                {
                    theta = (float)((i / 3) + 45);          //極座標系往直角座標系轉換
                    lengthX = length * (float)(Math.Cos(Math.PI * theta / 180));
                    lengthY = length * (float)(Math.Sin(Math.PI * theta / 180));
                    pointX.Add(lengthX);
                    pointY.Add(lengthY);
                    ArrPoint_X[ArrPoint_Count] = lengthX;
                    ArrPoint_Y[ArrPoint_Count] = lengthY;
                    ArrPoint_Count++;
                }
            }

            float averagex = 0, averagey = 0;
            foreach (float i in pointX)
            {
                averagex += i;
            }
            foreach (float j in pointY)
            {
                averagey += j;
            }
            averagex /= pointX.Count;        //  取X座標的平均數
            averagey /= pointY.Count;        //  取Y座標的平均數

            //經驗迴歸係數的分子與分母
            float numerator = 0;
            float denominator = 0;
            for (int i = 0; i < pointX.Count; i++)
            {
                numerator += (ArrPoint_X[i] - averagex) * (ArrPoint_Y[i] - averagey);
                denominator += (ArrPoint_X[i] - averagex) * (ArrPoint_X[i] - averagex);
            }
            //迴歸係數b(Regression Coefficient)   y = bx + a ;
            float RCB = numerator / denominator;
            //迴歸係數a
            float RCA = averagey - RCB * averagex;