亲宝软件园·资讯

展开

C#最小二乘法拟合曲线成直线的实例

yangzm996 人气:0

最小二乘法拟合曲线成直线

效果

传入X轴和Y轴的数据,得到新的Y轴数据。

将X值数据和拟合后的Y轴数据绑带即可。

 /// <summary>
        /// 最小二乘法/线性回归,得到新的点
        /// </summary>
        /// <param name="Points"></param>
        /// <param name="err"></param>
        /// <returns></returns>
        private List<double> LinearRegression(List<double> PointsX, List<double> PointsY)
        {
            List<double> Result = null;
            if (PointsX.Count < 2 || PointsY.Count < 2 || PointsX.Count != PointsY.Count)
            {
                return Result;
            }
            double Averagex = 0, Averagey = 0;
            for (int i = 0; i < PointsX.Count; i++)
            {
                Averagex += PointsX[i];
                Averagey += PointsY[i];
            }
            Averagex /= PointsX.Count;
            Averagey /= PointsX.Count;
            double Numerator = 0, Denominator = 0;
            for (int i = 0; i < PointsX.Count; i++)
            {
                Numerator += (PointsX[i] - Averagex) * (PointsY[i] - Averagey);
                Denominator += (PointsX[i] - Averagex) * (PointsX[i] - Averagex);
            }
            double K = Numerator / Denominator;
            double B = Averagey - K * Averagex;
            List<double> temp = new List<double>();
            foreach (var item in PointsX)
            {
                temp.Add(K * item + B);
            }
            Result = temp.ToList();
            return Result;
        }

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

加载全部内容

相关教程
猜你喜欢
用户评论