public
Last active

Linear regression in C#

  • Download Gist
gistfile1.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
/// <summary>
/// Fits a line to a collection of (x,y) points.
/// </summary>
/// <param name="xVals">The x-axis values.</param>
/// <param name="yVals">The y-axis values.</param>
/// <param name="inclusiveStart">The inclusive inclusiveStart index.</param>
/// <param name="exclusiveEnd">The exclusive exclusiveEnd index.</param>
/// <param name="rsquared">The r^2 value of the line.</param>
/// <param name="yintercept">The y-intercept value of the line (i.e. y = ax + b, yintercept is b).</param>
/// <param name="slope">The slop of the line (i.e. y = ax + b, slope is a).</param>
public static void LinearRegression(double[] xVals, double[] yVals,
int inclusiveStart, int exclusiveEnd,
out double rsquared, out double yintercept,
out double slope)
{
Debug.Assert(xVals.Length == yVals.Length);
double sumOfX = 0;
double sumOfY = 0;
double sumOfXSq = 0;
double sumOfYSq = 0;
double ssX = 0;
double ssY = 0;
double sumCodeviates = 0;
double sCo = 0;
double count = exclusiveEnd - inclusiveStart;
 
for (int ctr = inclusiveStart; ctr < exclusiveEnd; ctr++)
{
double x = xVals[ctr];
double y = yVals[ctr];
sumCodeviates += x * y;
sumOfX += x;
sumOfY += y;
sumOfXSq += x * x;
sumOfYSq += y * y;
}
ssX = sumOfXSq - ((sumOfX * sumOfX) / count);
ssY = sumOfYSq - ((sumOfY * sumOfY) / count);
double RNumerator = (count * sumCodeviates) - (sumOfX * sumOfY);
double RDenom = (count * sumOfXSq - (sumOfX * sumOfX))
* (count * sumOfYSq - (sumOfY * sumOfY));
sCo = sumCodeviates - ((sumOfX * sumOfY) / count);
 
double meanX = sumOfX / count;
double meanY = sumOfY / count;
double dblR = RNumerator / Math.Sqrt(RDenom);
rsquared = dblR * dblR;
yintercept = meanY - ((sCo / ssX) * meanX);
slope = sCo / ssX;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.