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 63
|
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
using namespace std;
//======================================================================
void regression( const vector<double> &x, const vector<double> &y, double &m, double &c, double &rho )
{
int N = x.size();
double Sx = 0, Sy = 0, Sxx = 0, Syy = 0, Sxy = 0;
for ( int i = 0; i < N; i++ )
{
Sx += x[i];
Sy += y[i];
Sxx += x[i] * x[i];
Syy += y[i] * y[i];
Sxy += x[i] * y[i];
}
double varxx = Sxx - Sx * Sx / N, varyy = Syy - Sy * Sy / N, varxy = Sxy - Sx * Sy / N;
m = varxy / varxx;
c = ( Sy - m * Sx ) / N;
rho = varxy / sqrt( varxx * varyy );
}
//======================================================================
double interpolation( const vector<double> &x, const vector<double> &y, double xval ) // x sorted and increasing
{
int i = 0, N = x.size();
if ( xval >= x[N-1] )
i = N - 2;
else if ( xval > x[0] )
while( x[i+1] < xval ) i++;
return y[i] + ( xval - x[i] ) * ( y[i+1] - y[i] ) / ( x[i+1] - x[i] );
}
//======================================================================
int main()
{
vector<double> x, y;
ifstream in( "input.txt" );
for ( double xpt, ypt; in >> xpt >> ypt; )
{
x.push_back( xpt );
y.push_back( ypt );
}
double m, c, rho;
regression( x, y, m, c, rho );
cout << "Linear regression line y = mx + c\n"
<< " m = " << m << '\n'
<< " c = " << c << '\n'
<< "Correlation coefficient rho = " << rho << "\n\n";
double test = 8.5;
cout << "At test value " << test << '\n'
<< " linear regression gives y = " << m * test + c << '\n'
<< " interpolation gives y = " << interpolation( x, y, test ) << '\n';
}
|