Instantly share code, notes, and snippets.

# tansey/gist:1375526 Created Nov 18, 2011

Linear regression in C#
 /// /// Fits a line to a collection of (x,y) points. /// /// The x-axis values. /// The y-axis values. /// The inclusive inclusiveStart index. /// The exclusive exclusiveEnd index. /// The r^2 value of the line. /// The y-intercept value of the line (i.e. y = ax + b, yintercept is b). /// The slop of the line (i.e. y = ax + b, slope is a). 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; }

### dsherret commented Jun 5, 2014

 What licence is this code released under?

### remixie commented Oct 11, 2017

 @tansey Is this code free for commercial use?