source: tags/release-1.0.5/src/Utils/linear_regression.cc @ 1455

Last change on this file since 1455 was 177, checked in by Matthew Whiting, 18 years ago

Some minor fixes to code:

  • Fixed potential bug in Cube::initialiseCube
  • Fixed #include commands for the Detect functions
  • Tidied up linear_regression.cc
  • Renamed cubicSearch.cc to CubicSearch?.cc and changed Makefile.in to match.
File size: 1.9 KB
Line 
1#include <iostream>
2#include <math.h>
3int linear_regression(int num, float *x, float *y, int ilow, int ihigh, float &slope, float &errSlope, float &intercept, float &errIntercept, float &r)
4{
5  /**
6   *  int linear_regression()
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.
14   * If everything works, returns 0.
15   * If slope is infinite (eg, all points have same x value), returns 1.
16   */
17
18  if (ilow>ihigh) {
19    std::cerr << "Error! linear_regression.cc :: ilow (" << ilow
20              << ") > ihigh (" << ihigh << ")!!\n";
21    return 1;
22  }
23  if (ihigh>num-1) {
24    std::cerr << "Error! linear_regression.cc :: ihigh (" <<ihigh
25              << ") out of bounds of array (>" << num-1 << ")!!\n";
26    return 1;
27  }
28  if(ilow<0){
29    std::cerr << "Error! linear_regression.cc :: ilow (" << ilow
30              << ") < 0. !!\n";
31    return 1;
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
50  const float SMALLTHING=1.e-6;
51  if(fabs(count*sumxx-sumx*sumx)<SMALLTHING) return 1;
52  else{
53
54    slope = (count*sumxy - sumx*sumy)/(count*sumxx - sumx*sumx);
55    errSlope = count / (count*sumxx - sumx*sumx);
56
57    intercept = (sumy*sumxx - sumxy*sumx)/(count*sumxx - sumx*sumx);
58    errIntercept = sumxx / (count*sumxx - sumx*sumx);
59   
60    r = (count*sumxy - sumx*sumy) /
61      (sqrt(count*sumxx-sumx*sumx) * sqrt(count*sumyy-sumy*sumy) );
62
63    return 0;
64
65  }
66}
Note: See TracBrowser for help on using the repository browser.