StRoot  1
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Groups Pages
LinearFit.h
1 #include <map>
2 #include <stdexcept>
3 #include <string>
4 #include <math.h>
5 using namespace std;
6 template<typename Number>
7 class LinearFit
8 {
9 public:
10  typedef std::map<Number, Number> Points;
11  LinearFit();
12  LinearFit(Points * points);
13  LinearFit(const LinearFit & fit);
14  virtual ~LinearFit();
15  const LinearFit & operator=(const LinearFit & fit);
16  virtual void fit();
17  virtual void fit(Points * points);
18  const Number getSlope() const;
19  const Number getIntercept() const;
20  const Number getRegressionCoefficient() const;
21 protected:
22  Points * _points;
24  Number _a;
26  Number _b;
28  Number _r;
29 };
30 
31 template<typename Number>
33 : _points(0), _a(0), _b(0), _r(0)
34 {}
35 
36 template<typename Number>
37 LinearFit<Number>::LinearFit(Points * points)
38 : _points(points), _a(0), _b(0), _r(0)
39 {}
40 
41 template<typename Number>
43 : _points(fit._points), _a(fit._a), _b(fit._b), _r(fit._r)
44 {}
45 
46 template<typename Number>
48 {
49  _points = fit._points;
50  _a = fit._a;
51  _b = fit._b;
52  _r = fit._r;
53 
54  return *this;
55 }
56 
60 template<typename Number>
61 void LinearFit<Number>::fit(Points * points)
62 {
63  _points = points;
64  _a = _b = _r = 0;
65  fit();
66 }
67 
68 template<typename Number>
70 {
71  int n = _points->size();
72  if (n < 2)
73  throw runtime_error("LinearFit<Number>::fit() - FATAL - n<2");
74  Number sumx=0,sumy=0,sumx2=0,sumy2=0,sumxy=0;
75  Number x, y,sxx,syy,sxy;
76  // Compute error matrix
77  typename std::map<Number, Number>::const_iterator i;
78  for (i = _points->begin(); i != _points->end(); i++)
79  {
80  x = i->first;
81  y = i->second;
82  sumx += x;
83  sumy += y;
84  sumx2 += (x*x);
85  sumy2 += (y*y);
86  sumxy += (x*y);
87  }
88  sxx = sumx2 - (sumx * sumx / n);
89  syy = sumy2 - (sumy * sumy / n);
90  sxy = sumxy - (sumx * sumy / n);
91  // Infinite slope_, non existant yIntercept
92  if (fabs(sxx) == 0)
93  {
94  _a = -99999.;
95  _b = -99999.;
96  _r = -99999.;
97  return;
98  }
99  // Calculate the slope_ and yIntercept
100  _a = sxy/sxx;
101  _b = sumy/n - _a*sumx/n;
102  // Compute the regression coefficient
103  if (fabs(syy) == 0)
104  _r = 1;
105  else
106  _r = sxy/::sqrt(sxx*syy);
107 }
108 
109 template<typename Number>
111 {}
112 
113 template<typename Number>
114 inline const Number LinearFit<Number>::getSlope() const
115 {
116  return _a;
117 }
118 
119 template<typename Number>
120 inline const Number LinearFit<Number>::getIntercept() const
121 {
122  return _b;
123 }
124 
125 template<typename Number>
126 inline const Number LinearFit<Number>::getRegressionCoefficient() const
127 {
128  return _r;
129 }
130 
Number _a
Slope.
Definition: LinearFit.h:24
Number _r
Regression.
Definition: LinearFit.h:28
Number _b
Intercept.
Definition: LinearFit.h:26