#include<iostream>
#include<math.h>
struct abr
{
double a;
double b;
double r2;
};
using namespace std;
double sum(double x[], int n, int f)
{
double s = 0;
for (int i = 0; i < n; i++)
{
s += pow(x[i], f);
}
return s;
}
double _sum(double x[], double y[], int n)
{
double s = 0;
for (int i = 0; i < n; i++)
{
s += x[i] * y[i];
}
return s;
}
void LinearFit(double x[], double y[], int n, abr L)
{
double xsum = 0, ysum = 0, x2sum = 0, xysum=0;
xsum = sum(x, n,1);
ysum = sum(y, n,1);
x2sum = sum(x,n,2);
xysum = _sum(x, y, n);
L.a = (n * xysum - xsum * ysum) / (n * x2sum - xsum * xsum);
L.b = (ysum - L.a * xsum) / n;
double yavge = ysum / n;
}
double Lf(abr L, double x)
{
return L.a * x + L.b;
}
double lose(double x[], double y[], int n, abr L)
{
double yavge = sum(y, n, 1) / n;
double dysum1 = 0, dysum2 = 0;
for (int i = 0; i < n; i++)
{
dysum1 += (Lf(L, x[i]) - yavge) * (Lf(L, x[i]) - yavge);
dysum2 += (y[i] - yavge) * (y[i] - yavge);
}
L.r2 = dysum1 / dysum2;
return L.r2;
}
double tf(double x)
{
return 2*x + 4;
}
int main()
{
struct abr L ;
double x[100], y[100];
for (int i = 0;i < 10;i++)
{
x[i] = i + 1.5;
y[i] = tf(x[i]);
}
LinearFit(x, y, 10,L);
cout << L.a << " " << L.b << " " << endl;
cout <<lose(x, y, 10, L) << endl;
system("pause");
}