source: branches/fitshead-branch/Utils/linear_regression.cc @ 1441

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

Added some new statistical routines for analysis use:
getStats.cc -- added findMinMax and findTrimmedStats-related routines.
get_random_spectrum.cc -- getNormalRVtrunc(), to find randomly distributed

variables from a truncated normal distribution.

linear_regression.cc -- changed type of routine to int
utils.hh -- updated prototype definitions.

File size: 2.0 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    std::exit(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    std::exit(1);
27  }
28  if(ilow<0){
29    std::cerr << "Error! linear_regression.cc :: ilow (" << ilow
30              << ") < 0. !!\n";
31    std::exit(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  if(count!=(ihigh-ilow+1)){
50    std::cerr << "Whoops!! count (" << count <<") doesn't equal what it should ("
51              << (ihigh-ilow+1) << ")!!\n";
52    std::exit(1);
53  }
54
55  if(fabs(count*sumxx-sumx*sumx)<1.e-6) return 1;
56  else{
57    slope = (count*sumxy - sumx*sumy)/(count*sumxx - sumx*sumx);
58    errSlope = count / (count*sumxx - sumx*sumx);
59    intercept = (sumy*sumxx - sumxy*sumx)/(count*sumxx - sumx*sumx);
60    errIntercept = sumxx / (count*sumxx - sumx*sumx);
61   
62    r = (count*sumxy - sumx*sumy)/(sqrt(count*sumxx-sumx*sumx)*sqrt(count*sumyy-sumy*sumy));
63    return 0;
64  }
65}
Note: See TracBrowser for help on using the repository browser.