C#最小二乘法拟合曲线成直线的实例
作者:yangzm996
这篇文章主要介绍了C#最小二乘法拟合曲线成直线的实例,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
最小二乘法拟合曲线成直线
效果
- 拟合前
- 拟合后
传入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; }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。