经典最小二乘法
1/* 2最小二乘法C++实现
3参数1为输入文件
4输入 : x
5输出: 预测的y
6*/ 7#include
8#include 9#include10usingnamespace std;
1112class LeastSquare{
13double a, b;
14public:
15LeastSquare(constvector<double>& x,constvector<double>& y)
16 {
17doublet1=0, t2=0, t3=0, t4=0;
18for(inti=0; ii)
19 {
20t1 += x[i]*x[i];
21t2 += x[i];
22t3 += x[i]*y[i];
23t4 += y[i];
24 }
25a = (t3*x.size() - t2*t4) / (t1*x.size() - t2*t2);// 求得β1 26b = (t1*t4 - t2*t3) / (t1*x.size() - t2*t2);// 求得β227 }
2829doublegetY(constdoublex)const30 {
31returna*x + b;
32 }
3334voidprint()const35 {
36cout<<"y = "<"x + "<"\n";
37 }
3839};
4041intmain(intargc,char*argv[])
42{
43if(argc !=2)
44 {
45cout<<"Usage: DataFile.txt"<<endl;
46return-1;
47 }
48else49 {
50vector<double> x;
51ifstreamin(argv[1]);
52for(doubled;in>>d; )
53 x.push_back(d);
54intsz = x.size();
55vector<double> y(x.begin()+sz/2, x.end());
56x.resize(sz/2);
57 LeastSquare ls(x, y);
58 ls.print();
5960cout<<"Input x:\n";
61double x0;
62while(cin>>x0)
63 {
64cout<<"y = "<endl;
65cout<<"Input x:\n";
66 }
67 }
68}
来源: http://www.bubuko.com/infodetail-1967783.html