C++最小二乘计算线性回归方程
2020-04-29 本文已影响0人
无聊的CairBin
介绍
用来理解一下数学思路和练习一下代码。即兴而写的,所以没写注释。
timg2.jpg
代码
#include <iostream>
// #include "Windows.h"
double sum_square_x = 0;
double sum_x = 0;
double sum_y = 0;
double sum_xy = 0;
int n = 0;
double ave_x = 0;
double ave_y = 0;
double b_ba = 0;
double a_ba = 0;
using namespace std;
void InputAndSum()
{
cout << "请输入n的值" << endl;
cin >> n;
cout << " " << endl;
double data_x = 0;
double data_y = 0;
int i = 1;
while (i <= n)
{
cout << "请输入第" << i << "个数据的x值" << endl;
cin >> data_x;
cout << " " << endl;
cout << "请输入第" << i << "个数据的y值" << endl;
cin >> data_y;
cout << " " << endl;
sum_x += data_x;
sum_y += data_y;
sum_xy += (data_x * data_y);
sum_square_x += (data_x * data_x);
i++;
}
}
double Average(double a)
{
double ave = a / n;
return ave;
}
double B_ba(double calc1,double calc2)
{
double square_ave_x = calc1 * calc1;
double calc3;
calc3 = (sum_xy - n * calc1 * calc2) / (sum_square_x - n * square_ave_x);
return calc3;
}
void A_ba()
{
a_ba = ave_y - b_ba * ave_x;
}
int main()
{
InputAndSum();
ave_x = Average(sum_x);
ave_y = Average(sum_y);
b_ba = B_ba(ave_x,ave_y);
A_ba();
cout << "---------------------------------" << endl;
cout << "---------------------------------" << endl;
cout << "n的值为: " << n << endl;
cout << "各x的和为: " << sum_x << endl;
cout << "各y的和为: " << sum_y << endl;
cout << "各个xy乘积的求和为: " << sum_xy << endl;
cout << "各个x平方的求和为: " << sum_xy << endl;
cout << "x的均值为: " << ave_x << endl;
cout << "y的均值为: " << ave_y << endl;
cout << "a(ba)为: " << a_ba << endl;
cout << "b(ba)为: " << b_ba << endl;
cout << "样本点中心为:(" << ave_x << "," << ave_y << ")" << endl;
cout << "回归直线方程为 y = " << b_ba << "x + " << "(" << a_ba << ")" << endl;
cout << "---------------------------------" << endl;
cout << "---------------------------------" << endl;
//system("pause");
}