最小二乘法在简单线性情况下的例子,c#

来源:互联网 发布:mac不能缓冲优酷视频 编辑:程序博客网 时间:2024/05/21 18:46

google了一下,这回高数算补回来了。以下是大致思路

假如给定的实验数据点为(Xi,Yi),其中i=0,1,...n,那么 直线与数据点的偏差平方和为

                                          


要使得

取到极小值,则要求:


,    

这两个式子是取得极小值的必要条件,具体运算的过程如下:


对该式求解得到:


<!--[if !vml]--><!--[endif]-->

以下就是我用C#做的源代码:
 
public class LeastSquare
    {
        
/// <summary>
        
/// To Draw Linear Least Square Fitting Curve 
        
/// </summary>
        
/// <param name="g">The device on which to draw the curve</param>
        
/// <param name="lp">A list of point used to do the approximation</param>
        public static void LeastSquare2(Graphics g, List<PointF> lp)
        {
            
// Clear the client window with the white color
            g.Clear(Color.White);

            
// Move the drawing origin to the point(200,200)
            g.TranslateTransform(200200);

            
// Use FillEllipse method to draw each point as an ellipse
            foreach (PointF p in lp)
            {
                g.FillEllipse(Brushes.Red, 
new RectangleF(p.X - 5.0f, p.Y - 5.0f10.0f10.0f));
            }


            
int i;
            
float a, b, sumX, sumY2, sumY, sumXY;
            sumX 
= 0.0f;
            sumY2 
= 0.0f;
            sumY 
= 0.0f;
            sumXY 
= 0.0f;

            
// To calculate as per the description of the Mathematical Formular
            for (i = 0; i < lp.Count; i++)
            {
                sumY 
+= lp[i].Y;
                sumY2 
+= lp[i].Y * lp[i].Y;
                sumX 
+= lp[i].X;
                sumXY 
+= lp[i].X * lp[i].Y;
            }

            
// Deduct the coefficients required to do the approximation using the mathematical formular
            a = (lp.Count * sumXY - sumX * sumY) / (lp.Count * sumY2 - sumY * sumY);
            b 
= (sumY2 * sumX - sumY * sumXY) / (lp.Count * sumY2 - sumY * sumY);

            Pen newPen 
= new Pen(Color.Blue, 3.0f);
            g.DrawLine(newPen, 
new PointF(0-/ a), new PointF(360, (360 - b) / a));
        }
    }
 
 
调用部分:
 // Declare a list of points
            List<PointF> lp = new List<PointF>();

            
// PointF array
            PointF[] pf = new PointF[]{
                
new PointF(0.0f,68.0f),
                
new PointF(10.0f,73.1f),new PointF(20.0f,66.4f),
                
new PointF(30.0f,70.6f),new PointF(40.0f,64.6f),
                
new PointF(50.0f,68.8f),new PointF(60.0f,61.0f),
                
new PointF(70.0f,65.8f),new PointF(80.0f,60.4f),
                
new PointF(90.0f,61.0f)
            };

            
// Using AddRange method of the list to add the pointf array to the end of the list
            lp.AddRange(pf);

            
// Call the static metod LeastSquare2 of LeastSquare Class to proceed
            LeastSquare.LeastSquare2(this.CreateGraphics(), lp);
原创粉丝点击