source: tags/release-0.9/Utils/linear_regression.cc @ 813

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

This is the first full import of all working code to
the Duchamp repository.
Made three directories at top level:

branches/ tags/ trunk/

and trunk/ has the full set of code:
ATrous/ Cubes/ Detection/ InputComplete? InputExample? README Utils/ docs/ mainDuchamp.cc param.cc param.hh

File size: 1.8 KB
Line 
1#include <iostream>
2#include <math.h>
3void 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   *   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   */
15
16  if (ilow>ihigh) {
17    std::cerr << "Error! linear_regression.cc :: ilow (" << ilow
18              << ") > ihigh (" << ihigh << ")!!\n";
19    std::exit(1);
20  }
21  if (ihigh>num-1) {
22    std::cerr << "Error! linear_regression.cc :: ihigh (" <<ihigh
23              << ") out of bounds of array (>" << num-1 << ")!!\n";
24    std::exit(1);
25  }
26  if(ilow<0){
27    std::cerr << "Error! linear_regression.cc :: ilow (" << ilow
28              << ") < 0. !!\n";
29    std::exit(1);
30  }
31
32  double sumx,sumy,sumxx,sumxy,sumyy;
33  sumx=0.;
34  sumy=0.;
35  sumxx=0.;
36  sumxy=0.;
37  sumyy=0.;
38  int count=0;
39  for (int i=ilow;i<=ihigh;i++){
40    count++;
41    sumx = sumx + x[i];
42    sumy = sumy + y[i];
43    sumxx = sumxx + x[i]*x[i];
44    sumxy = sumxy + x[i]*y[i];
45    sumyy = sumyy + y[i]*y[i];
46  }
47  if(count!=(ihigh-ilow+1)){
48    std::cerr << "Whoops!! count (" << count <<") doesn't equal what it should ("
49              << (ihigh-ilow+1) << ")!!\n";
50    std::exit(1);
51  }
52
53  slope = (count*sumxy - sumx*sumy)/(count*sumxx - sumx*sumx);
54  errSlope = count / (count*sumxx - sumx*sumx);
55  intercept = (sumy*sumxx - sumxy*sumx)/(count*sumxx - sumx*sumx);
56  errIntercept = sumxx / (count*sumxx - sumx*sumx);
57
58  r = (count*sumxy - sumx*sumy)/(sqrt(count*sumxx-sumx*sumx)*sqrt(count*sumyy-sumy*sumy));
59}
Note: See TracBrowser for help on using the repository browser.