最小二乘法实现C++
来源:http://blog.csdn.net/qll125596718/article/details/8248249
求a、b的值:
- // Ordinary Least Square.cpp : 定义控制台应用程序的入口点。
- //
- #include "stdafx.h"
- #include <iostream>
- #include <fstream>
- #include <vector>
- using namespace std;
- 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
- {
- 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;)//将读取出来的数值全部存入容器X中
- {
- x.push_back(d);//push_back()是把一个元素,放入这个容器的末尾,相当于末尾添加一个元素
- }
- int sz = x.size();
- vector<double> y(x.begin() + sz / 2, x.end());//把余下的容器X中的元素全部放进容器Y
- x.resize(sz / 2);//调整容器X的长度大小,超过当前size的元素删除
- LeastSquare ls(x, y);//调用最小二乘法求a和b
- ls.print();
- cout << "Input x:\n";
- double x0;
- while (cin >> x0)
- {
- cout << "y = " << ls.getY(x0) << endl;
- cout << "Input x:\n";
- }
- }
- return 0;
- }
实验模拟数据:
10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 |
2000.36 | 2000.50 | 2000.72 | 2000.80 | 2001.07 | 2001.25 | 2001.48 | 2001.60 |
实验结果:

浙公网安备 33010602011771号