-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinear_regression.cpp
62 lines (59 loc) · 1.3 KB
/
linear_regression.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include<bits/stdc++.h>
using namespace std;
vector<double> x, y;
int n;
const double eps = 0.001;
void printPoly(int n, double a[]) {
cout << fixed << setprecision(3);
while (n >= 0 && fabs(a[n]) < eps) {
n--;
}
if (n < 0) {
cout << 0;
return;
}
for (int i = n; i >= 0; i--) {
if (fabs(a[i]) < eps) {
continue;
}
if (a[i] > 0 && i < n) {
cout << "+";
}
if (1-eps > fabs(a[i]) || fabs(a[i]) > 1+eps || i == 0) {
cout << a[i];
} else if (-1-eps < a[i] && a[i] < -1+eps) {
cout << "-";
}
if (i > 1) {
cout << "x^" << i;
} else if (i == 1) {
cout << "x";
}
}
}
int main() {
cin >> n;
x.push_back(0);
y.push_back(0);
for (int i = 1, _x, _y; i <= n; i++) {
cin >> _x >> _y;
x.push_back(_x);
y.push_back(_y);
}
double sx = 0;
double sy = 0;
double sxy = 0;
double sx2 = 0;
for (int i = 1; i <= n; i++) {
sx += x[i];
sy += y[i];
sxy += x[i]*y[i];
sx2 += x[i]*x[i];
}
double k = (n*sxy-sx*sy) / (n*sx2-sx*sx);
double b = sy/n - sx/n*k;
double a[] = {b, k};
cout << "y=";
printPoly(1, a);
return 0;
}