[3] | 1 | #include <iostream> |
---|
| 2 | #include <math.h> |
---|
[70] | 3 | int linear_regression(int num, float *x, float *y, int ilow, int ihigh, float &slope, float &errSlope, float &intercept, float &errIntercept, float &r) |
---|
[3] | 4 | { |
---|
| 5 | /** |
---|
[70] | 6 | * int linear_regression() |
---|
[3] | 7 | * |
---|
| 8 | * Computes the linear best fit to data - y = a*x + b, where x and y are |
---|
| 9 | * arrays of size num, a is the slope and b the y-intercept. |
---|
| 10 | * The values used in the arrays are those from ilow to ihigh. |
---|
| 11 | * (ie. if the full arrays are being used, then ilow=0 and ihigh=num-1. |
---|
| 12 | * Returns the values of slope & intercept (with errors) |
---|
| 13 | * as well as r, the regression coefficient. |
---|
[70] | 14 | * If everything works, returns 0. |
---|
| 15 | * If slope is infinite (eg, all points have same x value), returns 1. |
---|
[3] | 16 | */ |
---|
| 17 | |
---|
| 18 | if (ilow>ihigh) { |
---|
| 19 | std::cerr << "Error! linear_regression.cc :: ilow (" << ilow |
---|
| 20 | << ") > ihigh (" << ihigh << ")!!\n"; |
---|
[177] | 21 | return 1; |
---|
[3] | 22 | } |
---|
| 23 | if (ihigh>num-1) { |
---|
| 24 | std::cerr << "Error! linear_regression.cc :: ihigh (" <<ihigh |
---|
| 25 | << ") out of bounds of array (>" << num-1 << ")!!\n"; |
---|
[177] | 26 | return 1; |
---|
[3] | 27 | } |
---|
| 28 | if(ilow<0){ |
---|
| 29 | std::cerr << "Error! linear_regression.cc :: ilow (" << ilow |
---|
| 30 | << ") < 0. !!\n"; |
---|
[177] | 31 | return 1; |
---|
[3] | 32 | } |
---|
| 33 | |
---|
| 34 | double sumx,sumy,sumxx,sumxy,sumyy; |
---|
| 35 | sumx=0.; |
---|
| 36 | sumy=0.; |
---|
| 37 | sumxx=0.; |
---|
| 38 | sumxy=0.; |
---|
| 39 | sumyy=0.; |
---|
| 40 | int count=0; |
---|
| 41 | for (int i=ilow;i<=ihigh;i++){ |
---|
| 42 | count++; |
---|
| 43 | sumx = sumx + x[i]; |
---|
| 44 | sumy = sumy + y[i]; |
---|
| 45 | sumxx = sumxx + x[i]*x[i]; |
---|
| 46 | sumxy = sumxy + x[i]*y[i]; |
---|
| 47 | sumyy = sumyy + y[i]*y[i]; |
---|
| 48 | } |
---|
| 49 | |
---|
[177] | 50 | const float SMALLTHING=1.e-6; |
---|
| 51 | if(fabs(count*sumxx-sumx*sumx)<SMALLTHING) return 1; |
---|
[70] | 52 | else{ |
---|
[177] | 53 | |
---|
[70] | 54 | slope = (count*sumxy - sumx*sumy)/(count*sumxx - sumx*sumx); |
---|
| 55 | errSlope = count / (count*sumxx - sumx*sumx); |
---|
[177] | 56 | |
---|
[70] | 57 | intercept = (sumy*sumxx - sumxy*sumx)/(count*sumxx - sumx*sumx); |
---|
| 58 | errIntercept = sumxx / (count*sumxx - sumx*sumx); |
---|
| 59 | |
---|
[177] | 60 | r = (count*sumxy - sumx*sumy) / |
---|
| 61 | (sqrt(count*sumxx-sumx*sumx) * sqrt(count*sumyy-sumy*sumy) ); |
---|
| 62 | |
---|
[70] | 63 | return 0; |
---|
[177] | 64 | |
---|
[70] | 65 | } |
---|
[3] | 66 | } |
---|