1.原理:
2.代码:
class LeastSquare{
double a, b;
public:
LeastSquare(const vector<double>& x, const vector<double>& y)
{
double t1=0, t2=0, t3=0, t4=0;
for(int i=0; i<x.size(); ++i)
{
t1 += x[i]*x[i];
t2 += x[i];
t3 += x[i]*y[i];
t4 += y[i];
}
a = (t3*x.size() - t2*t4) / (t1*x.size() - t2*t2);
b = (t1*t4 - t2*t3) / (t1*x.size() - t2*t2);
}
double getY(const double x) const
{
return a*x + b;
}
void print() const
{
std::cout <<"y = "<<a<<"x + "<<b<<"\n";
}
};
3.注意事项:
x,y的值很大时,会造成t1,t3的值越界.