最小二乘法实现C++

早过忘川 提交于 2020-08-07 07:39:52

来源:http://blog.csdn.net/qll125596718/article/details/8248249

     

求a、b的值:

  1. // Ordinary Least Square.cpp : 定义控制台应用程序的入口点。
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include <iostream>
  6. #include <fstream>
  7. #include <vector>
  8. using namespace std;
  9.  
  10. class LeastSquare
  11. {
  12.    double a, b;
  13. public:
  14.    LeastSquare(const vector<double>& x, const vector<double>& y)//最小二乘法公式
  15.    {
  16.       double t1 = 0, t2 = 0, t3 = 0, t4 = 0;
  17.       for (int i = 0; i < x.size(); ++i)
  18.       {
  19.          t1 += x[i] * x[i];
  20.          t2 += x[i];
  21.          t3 += x[i] * y[i];
  22.          t4 += y[i];
  23.       }
  24.       a = (t3 * x.size() - t2 * t4) / (t1 * x.size() - t2 * t2);
  25.       b = (t1 * t4 - t2 * t3) / (t1 * x.size() - t2 * t2);
  26.    }
  27.  
  28.    double getY(const double x) const
  29.    {
  30.       return a * x + b;
  31.    }
  32.  
  33.    void print() const
  34.    {
  35.       cout << "y = " << a << "x + " << b << endl;
  36.    }
  37.  
  38. };
  39.  
  40.  
  41. int _tmain(int argc, _TCHAR* argv[])
  42. {
  43.    if (argc != 2)
  44.    {
  45.       cout << "Usage: DataFile.txt" << endl;
  46.       return -1;
  47.    }
  48.    else
  49.    {
  50.       vector<double> x;
  51.       ifstream in(argv[1]);
  52.       for (double d; in >> d;)//将读取出来的数值全部存入容器X中
  53.       {
  54.          x.push_back(d);//push_back()是把一个元素,放入这个容器的末尾,相当于末尾添加一个元素
  55.  
  56.       }
  57.       int sz = x.size();
  58.  
  59.       vector<double> y(x.begin() + sz / 2, x.end());//把余下的容器X中的元素全部放进容器Y
  60.       x.resize(sz / 2);//调整容器X的长度大小,超过当前size的元素删除
  61.       LeastSquare ls(x, y);//调用最小二乘法求a和b
  62.       ls.print();
  63.  
  64.       cout << "Input x:\n";
  65.       double x0;
  66.  
  67.       while (cin >> x0)
  68.       {
  69.          cout << "y = " << ls.getY(x0) << endl;
  70.          cout << "Input x:\n";
  71.       }
  72.    }
  73.    return 0;
  74. }

实验模拟数据:

10

15

20

25

30

35

40

45

2000.36

2000.50

2000.72

2000.80

2001.07

2001.25

2001.48

2001.60

实验结果:

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!