Here is an implementation of the Excel LINEST () function in C #. It returns the slope for a given dataset, normalized using the same least-squares method used in LINEST ():
public static double CalculateLinest(double[] y, double[] x) { double linest = 0; if (y.Length == x.Length) { double avgY = y.Average(); double avgX = x.Average(); double[] dividend = new double[y.Length]; double[] divisor = new double[y.Length]; for (int i = 0; i < y.Length; i++) { dividend[i] = (x[i] - avgX) * (y[i] - avgY); divisor[i] = Math.Pow((x[i] - avgX), 2); } linest = dividend.Sum() / divisor.Sum(); } return linest; }
Also described here is the method that I wrote to get the value of "b" (y-intercept) that the Excel LINEST function generates.
private double CalculateYIntercept(double[] x, double[] y, double linest) { return (y.Average() - linest * x.Average()); }
Since these methods only work for one dataset, I would recommend calling them inside a loop if you want to create multiple linear regression datasets.
This link helped me find my answer: https://agrawalreetesh.blogspot.com/2011/11/how-to-calculate-linest-of-given.html
source share