Fitting a straight line to a dataset

Problem: given sample data points (x_i,y_i), find a good straight line through the data y=mx+b with slope m and intercept b such that the sum of least squares is minimized.

Here you can find the following code:

double sx = 0.0, sy = 0.0, sxx = 0.0, sxy = 0.0;
int n = x.size();
for (int i = 0; i < n; ++i)
{
	sx += x[i];
	sy += y[i];
	sxx += x[i]*x[i];
	sxy += x[i]*y[i];
}
double delta = n*sxx - sx*sx;
double slope = (n*sxy - sx*sy)/delta;
double intercept = (sxx*sy - sx*sxy)/delta;
 
public/fitting_a_straight_line_to_a_dataset.txt · Last modified: 2013/02/22 15:50 (external edit) · []
Recent changes RSS feed Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki