linearRegression

控制台应用程序拟合回归方程

#ifndef _CUSTOMCLASS_
#define _CUSTOMCLASS_
#include <iostream>
#include <list>
#include <vector>
#include <iomanip>
#include <cmath>
using namespace std;
class Person {
public:
    long loginNum;
    long amount;
    double average;
    bool flag;
    Person(long LloginNum,long Lamout) {
        loginNum = LloginNum;
        amount = Lamout;
        flag = false;

        try{
            if (loginNum <= 0 || amount < 0)
                throw runtime_error("PAREMETER ERROR");
        }catch (runtime_error err){
            flag = true;
        }
        if (!flag) {
            average =(double) amount /(double) loginNum;
        }
    }
    void show();
   
};
list<Person>& clear(list<Person>& Lsinge);
void calculate(list<Person>& Lsingle, double *p);
#endif
#include "CustomClass.h"
/*
    最小二乘法法拟合回归方程
*/

int main() {
   
    list<Person> single;
    long inputlogin;
    long inputamout;
    double func[2];
    /*步骤1 获取数据*/
    while (cin >> inputlogin >> inputamout) {
        Person tmSingle(inputlogin, inputamout);
        single.push_back(tmSingle);
    }
    /*步骤2 清洗数据*/
    clear(single);
    /*步骤3 打印数据数据是否清晰干净*/
    for (auto i : single) {
        i.show();
    }
    /*步骤4 建立回归方程*/
    calculate(single, func);
    cout << func[0] << endl;
    cout << func[1] << endl;
    /*步骤5 预测y值*/
    double x;
    double y;
    cin.clear();
    cout << "请输入一个x来拟合其y值:" << endl;
    cin >> x;
    cout << "预测y值为:";
    y = func[0] * x + func[1];
    cout << y << endl;
    system("pause");
    return 0;
}
list<Person>& clear(list<Person>& Lsingle) {
    list<Person>::iterator it,tmit;
    for (it = Lsingle.begin(); it!=Lsingle.end();) {
        if ((*it).flag)
            it=Lsingle.erase(it);
        else
            it++;
    }
    return Lsingle;
}
void calculate(list<Person>& Lsingle,double *p) {
    double a = 0;
    double l = 0;
    double sum1 = 0;
    double sum2 = 0;
    for (auto i : Lsingle) {
        a += i.amount;      
        l += i.loginNum;    
    }
    a /= Lsingle.size();   //y
    l /= Lsingle.size();   //x
    //拟合线性回归方程
    for (auto i : Lsingle) {
        sum1 += i.loginNum*i.amount;
        sum2 += pow(i.loginNum,2);
    }
    p[0] = (sum1 - Lsingle.size()*a*l) / (sum2 - Lsingle.size()*pow(l, 2));  //b
    p[1] = a - p[0] * l;  //a
}
void Person::show() {
    cout << setw(10) << "LoginNum:" << loginNum << "\t";
    cout << setw(10) << "amount:" << amount << "\t";
    cout << setw(10) << "average:" << average << endl;
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注