, , ..: http://faculty.cs.niu.edu/~hutchins/csci230/best-fit.htm. , ++ :
#include <vector>
#include <cmath>
struct Point {
double _x, _y;
};
struct Line {
double _slope, _yInt;
double getYforX(double x) {
return _slope*x + _yInt;
}
bool fitPoints(const std::vector<Point> &pts) {
int nPoints = pts.size();
if( nPoints < 2 ) {
return false;
}
double sumX=0, sumY=0, sumXY=0, sumX2=0;
for(int i=0; i<nPoints; i++) {
sumX += pts[i]._x;
sumY += pts[i]._y;
sumXY += pts[i]._x * pts[i]._y;
sumX2 += pts[i]._x * pts[i]._x;
}
double xMean = sumX / nPoints;
double yMean = sumY / nPoints;
double denominator = sumX2 - sumX * xMean;
if( std::fabs(denominator) < 1e-7 ) {
return false;
}
_slope = (sumXY - sumX * yMean) / denominator;
_yInt = yMean - _slope * xMean;
return true;
}
};
, , , (http://en.wikipedia.org/wiki/Simple_linear_regression#Fitting_the_regression_line) , "" . ,
y = k*x + b
. , " " , ,
A*x + B*y + C = 0
. :
y = k*x + b <=>
y - k*x - b = 0 <=>
B=1, A=-k, C=-b
:
B=1, A=-_slope, C=-_yInt
"then" if , 0, // Fail: it seems a vertical line, :
x = xMean <=>
x - xMean = 0 <=>
A=1, B=0, C=-xMean
, , , . - : http://hotmath.com/hotmath_help/topics/line-of-best-fit.html
double denominator = sumX2 - 2 * sumX * xMean + nPoints * xMean * xMean;
...
_slope = (sumXY - sumY*xMean - sumX * yMean + nPoints * xMean * yMean) / denominator;
, nPoints*xMean == sumX nPoints*xMean*yMean == sumX * yMean == sumY * xMean.