c#求slope线性回归斜率

时间:2021-07-06 00:59:10

public class mySlope
{
// public List<double> Values { get; set; }

public double SlopeResult { get; set; }

}
//-------------------------------------------------------------------------------------------------------------------------------
#region 计算slope
/// <summary>
/// Calculates slope()
/// </summary>
/// <param name="input">Input y_signal</param>
/// <param name="period">Number of periods</param>
/// <returns>Object containing operation results</returns>
public static mySlope Slope(IEnumerable<double> input_y, int period)
{ // var returnValues = new List<double>();
List<double> input_x = new List<double>();
for (int i = 1; i <= period; i++)
{
input_x.Add(i);

}

var copyInputValues_x = input_x.ToList();
var copyInputValues_y = input_y.ToList();
List<double> arr_xy=new List<double>();
List<double> arr_xx=new List<double>();
List<double> arr_x = new List<double>();
List<double> arr_y = new List<double>();
arr_x = copyInputValues_x;
for(int j=copyInputValues_y.Count-period;j<copyInputValues_y.Count;j++)
{

//arr_x.Add(copyInputValues_x[j]);
arr_y.Add(copyInputValues_y[j]);

}
double x_arr_dataAv = arr_x.Take(period).Average();
double y_arr_dataAv = arr_y.Take(period).Average();
for(int i=0;i<arr_x.Count;i++)
{
arr_x[i] = arr_x[i] - x_arr_dataAv;
arr_y[i] = arr_y[i] - y_arr_dataAv;
arr_xx.Add( arr_x[i] * arr_x[i]);
arr_xy.Add ( arr_y[i] * arr_x[i]);
}
double sumxx = arr_xx.Sum();
double sumxy = arr_xy.Sum();

var result = new mySlope()
{
SlopeResult = sumxy/sumxx,
// Values = returnValues,
};
return result;
}
#endregion

}