Skip to content

Instantly share code, notes, and snippets.

@xmichaelx
Created February 24, 2016 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xmichaelx/1a8f64402c0e253dc51e to your computer and use it in GitHub Desktop.
Save xmichaelx/1a8f64402c0e253dc51e to your computer and use it in GitHub Desktop.
Fitting line while minimizing least squares error
Tuple<double, double> LinearLeastSquaresFit(List<Point> points)
{
double length = points.Count;
double Sx = points.Sum(p=> p.X);
double Sy = points.Sum(p => p.Y);
double Sxx = points.Sum(p => Math.Pow(p.X,2));
double Sxy = points.Sum(p => p.X * p.Y);
var a = (Sxy * length - Sx * Sy) / (Sxx * length - Sx * Sx);
var b = (Sxy * Sx - Sy * Sxx) / (Sx * Sx - length * Sxx);
return new Tuple<double, double>(a, b);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment