线性二乘法求最接近的所有点的直线(log版)

public static void LeastSquaresFitLogOrdinate(MultiPointsList points, int numPoints, ref double M, ref double B)
        {

            //Gives best fit of data to curve Y = B*(10^M)^X  

            double x1, y1, xy, x2, J, LY;

            int i;

            x1 = 0.0;
            y1 = 0.0;
            xy = 0.0;
            x2 = 0.0;
            LY = 0.0;

            for (i = 0; i < numPoints; i++)
            {
                LY = Math.Log10(points[i].Y);
                x1 = x1 + points[i].X;
                y1 = y1 + LY;
                xy = xy + points[i].X * LY;
                x2 = x2 + points[i].X * points[i].X;

            }

            J = ((double)numPoints * x2) - (x1 * x1);

            if (J != 0.0)
            {
                M = (((double)numPoints * xy) - (x1 * y1)) / J;
                M = Math.Floor(1.0E3 * M + 0.5) / 1.0E3;
                B = ((y1 * x2) - (x1 * xy)) / J;
                B = Math.Floor(1.0E3 * B + 0.5) / 1.0E3;
            }
            else
            {
                M = 0;
                B = 0;
            }

        } 

 

posted @ 2013-02-17 10:37  东风125  阅读(270)  评论(0编辑  收藏  举报