Serge's World

Blogging about software development, astronomy, genealogy and more.

Maths Algorithms in C#: Linear Least Squares Fit

When analysing data it is often useful to find an equation to show the relationship in a certain set of data. The linear least squares fit tries to do exactly that.

Given a set of data points, it tries to find a straight line with the equation y = Mx + B which best fits the data, using the least squares technique, which works out the squares of the deviations of each point and then tries to minimize those.

public static void LeastSquaresFitLinear(List<Point> points, ref double m, ref double b)
{
	double x1, y1, xy, x2, j;

	x1 = y1 = xy = x2 = 0.0;

	foreach(Point point in points)
	{
		x1 += point.X;
		y1 += point.Y;
		xy += point.X * point.Y;
		x2 += point.X * point.X;
	}

	j = (points.Count * x2) - (x1 * x1);
	if (j != 0.0)
	{
		m = ((points.Count * xy) - (x1 * y1)) / j;
		b = ((y1 * x2) - (x1 * xy)) / j;
	}
	else
	{
		m = 0;
		b = 0;
	}
}

The full sourcecode for the MathLib library is available at https://github.com/sjmeunier/mathlib

Originally posted on my old blog, Smoky Cogs, on 23 Oct 2009

Updated 5 Oct 2016: Updated code snippet after refactoring MathLib library

Tag Cloud

Algorithms (3) Android (10) Astronomy (25) Audio (1) Audiobooks (1) Barcodes (9) C# (69) Css (1) Deep sky (6) Esoteric languages (3) Family (3) Fractals (10) Gaming (1) Genealogy (14) General (2) Geodesy (3) Google (1) Graphics (3) Hubble (2) Humour (1) Image processing (23) Java (8) Javascript (5) jQuery (3) Jupiter (3) Maths (22) Moon (5) Music (4) Pets (5) Programming (88) Saturn (1) Science (1) Spitzer (4) Sun (4) Tutorials (68) Unity (3) Web (9) Whisky (13) Windows (1) Xamarin (2)