問題情境:
一堆點求斜率,不能使用簡單的▲Y/▲X
解析思路:
求解:斜率——>線性回歸——>最小二乘法——>最優解——>偏導
驗證:相關系數r,統計量f,剩餘标準差s:r趨近于1好;f越大越好;s趨近于0好。
性質:
一定過點(Avgx,Avgy)。備注:x均值,y均值
代碼:
public static double slope(IEnumerable<int> input_y, int period)
{
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_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();
return Math.Round(sumxy / sumxx, 2);
}