这篇文章主要介绍了怎么使用C#最小二乘法拟合曲线成直线的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇怎么使用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;
}