【统计学】一元线性回归 Monadic Linear Regression
一元线性回归方程:
倾向值:
回归常量:
相关系数
协方差(Covariance)的计算公式:
C++源代码:
1 /* 2 3 App : LR.cpp 4 5 This is a C++ program 6 for linear regression 7 between x and t(time or year), 8 i.e. x = a + b * t 9 10 BY : ZXD 11 Date : January 9, 2014 12 13 */ 14 15 #define _CRT_SECURE_NO_WARNINGS 16 17 #include <fstream> 18 #include <cmath> 19 20 #define NSIZE 51 21 // The NSIZE is size of sample, 22 // e.i. the number of units. 23 24 void slr( int n, 25 double *x, 26 double *t, 27 double *xr, 28 double &a, 29 double &b, 30 double &r 31 ); 32 33 int main() 34 { 35 int n = NSIZE; 36 double x[NSIZE] = { 0 }; 37 double t[NSIZE] = { 0 }; 38 double xr[NSIZE] = { 0 }; 39 double a = 0; 40 double b = 0; 41 double r = 0; 42 43 FILE *infp; 44 FILE *outfp; 45 46 infp = fopen( "data4.txt", "r"); 47 for ( int i = 0; i < n; i++ ) 48 { 49 fscanf( infp, "%lf %lf", &t[i], &x[i] ); 50 //printf( "%10.4lf %10.4lf %10.4lf\n", t[i], x[i], xr[i] ); 51 } 52 fclose( infp ); 53 54 slr( n, x, t, xr, a, b, r ); 55 56 outfp = fopen( "result.txt", "w" ); 57 for ( int i = 0; i < n; i++ ) 58 { 59 fprintf( outfp, "%10.4lf %10.4lf %10.4lf\n", t[i], x[i], xr[i] ); 60 printf( "%10.4lf %10.4lf %10.4lf\n", t[i], x[i], xr[i] ); 61 } 62 63 fprintf( outfp, "\n" ); 64 fprintf( outfp, "Constant of regression : a = %10.4lf\n", a ); 65 fprintf( outfp, "Coefficient of regression : b = %10.4lf\n", b ); 66 fprintf( outfp, "Correlation Coefficient : r = %10.4lf\n", r ); 67 68 printf( "\n" ); 69 printf( "Constant of regression : a = %10.4lf\n", a ); 70 printf( "Coefficient of regression : b = %10.4lf\n", b ); 71 printf( "Correlation Coefficient : r = %10.4lf\n", r ); 72 73 fclose( outfp ); 74 75 system( "pause" ); 76 77 } 78 79 void slr( int n, 80 double *x, 81 double *t, 82 double *xr, 83 double &a, 84 double &b, 85 double &r 86 ) 87 { 88 double xSum = 0; 89 double tSum = 0; 90 91 double xxSum = 0; 92 double ttSum = 0; 93 double xtSum = 0; 94 95 // Covariance 96 double xxCov = 0; 97 double ttCov = 0; 98 double xtCov = 0; 99 100 for ( int i = 0; i < n; i++ ) 101 { 102 xSum += x[i]; 103 tSum += t[i]; 104 xxSum += x[i] * x[i]; 105 ttSum += t[i] * t[i]; 106 xtSum += x[i] * t[i]; 107 } 108 109 xxCov = xxSum - xSum * xSum / (double)n; 110 ttCov = ttSum - tSum * tSum / (double)n; 111 xtCov = xtSum - xSum * tSum / (double)n; 112 113 b = xtCov / ttCov; 114 a = xSum / (double)n - b * tSum / (double)n; 115 r = xtCov / sqrt( xxCov * ttCov ); 116 117 // Calculating regressand 118 for ( int i = 0; i < n; i++ ) 119 xr[i] = a + b * t[i]; 120 121 return; 122 }