Source: http://blog.csdn.net/qll125596718/article/details/8248249
??
Ask for A, B value:
Ordinary Least Square.cpp: Defines the entry point of the console application.
//
?
#include"stdafx.h"
#include<iostream>
#include<fstream>
#include<vector>
Usingnamespace std;
?
Class Leastsquare
{
???? Double A, b;
Public:
???? Leastsquare (const vector<Double>& x, const vector<double>& y) //Least Squares formula
???? {
???????? 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 (constdouble x) const
???? {
???????? return A * x + b;
????}
?
???? void print () const
???? {
???????? cout << "y =" << a << "x +" << b << endl;
????}
?
};
?
?
int _tmain (int argc, _tchar* argv[])
{
???? if (argc! = 2)
???? {
???????? cout << "Usage:DataFile.txt" << Endl;
???????? return -1;
????}
???? Else
???? {
???????? vector<Double> x;
???????? Ifstream in (argv[1]);
???????? for (double d, in >> D;)//To put the read value all in container x
???????? {
???????????? X.push_back (d); //push_back () is an element that is placed at the end of the container, which is equivalent to adding an element at the end
?
????????}
???????? int sz = x.size ();
?
???????? vector<Double> Y (x.begin () + SZ/2, x.end ()); Put all the elements in the remaining container x into the container y
???????? X.resize (SZ/2); //Adjust the length of container x to remove elements that exceed the current size
???????? Leastsquare ls (x, y); //Call the least squares to find a and b
???????? Ls.print ();
?
???????? cout << "Input x:\n";
???????? double x0;
?
???????? while (Cin >> x0)
???????? {
???????????? cout << "y =" << ls.gety (x0) << Endl;
???????????? cout << "Input x:\n";
????????}
????}
???? return 0;
}
?
Experimental simulation data:
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
2000.36 |
2000.50 |
2000.72 |
2000.80 |
2001.07 |
2001.25 |
2001.48 |
2001.60 |
Experimental results:
Implementation of C + + by least squares method