LArSoft  v09_90_00
Liquid Argon Software toolkit - https://larsoft.org/
LinFitAlg.cxx
Go to the documentation of this file.
1 
12 #include <math.h>
13 
14 namespace trkf {
15 
16  void LinFitAlg::LinFit(std::vector<float>& x,
17  std::vector<float>& y,
18  std::vector<float>& ey2,
19  float& Intercept,
20  float& Slope,
21  float& InterceptError,
22  float& SlopeError,
23  float& ChiDOF) const
24  {
25  // fit a line ala Bevington linfit.F. The number of points fit is defined by
26  // the size of the y vector.
27 
28  ChiDOF = 999.;
29 
30  if (y.size() < 2) return;
31  if (x.size() < y.size() || ey2.size() < y.size()) return;
32 
33  double sum = 0.;
34  double sumx = 0.;
35  double sumy = 0.;
36  double sumxy = 0.;
37  double sumx2 = 0.;
38  double sumy2 = 0.;
39  double weight, arg;
40  unsigned short ii;
41 
42  for (ii = 0; ii < y.size(); ++ii) {
43  weight = 1. / ey2[ii];
44  sum += weight;
45  sumx += weight * x[ii];
46  sumy += weight * y[ii];
47  sumx2 += weight * x[ii] * x[ii];
48  sumxy += weight * x[ii] * y[ii];
49  sumy2 += weight * y[ii] * y[ii];
50  }
51  // calculate coefficients and std dev
52  double delta = sum * sumx2 - sumx * sumx;
53  if (delta == 0.) return;
54  double A = (sumx2 * sumy - sumx * sumxy) / delta;
55  double B = (sumxy * sum - sumx * sumy) / delta;
56  Intercept = A;
57  Slope = B;
58  if (x.size() == 2) {
59  ChiDOF = 0.;
60  return;
61  }
62  double ndof = x.size() - 2;
63  double varnce =
64  (sumy2 + A * A * sum + B * B * sumx2 - 2 * (A * sumy + B * sumxy - A * B * sumx)) / ndof;
65  if (varnce > 0.) {
66  InterceptError = sqrt(varnce * sumx2 / delta);
67  SlopeError = sqrt(varnce * sum / delta);
68  }
69  else {
70  InterceptError = 0.;
71  SlopeError = 0.;
72  }
73  sum = 0.;
74  // calculate chisq
75  for (ii = 0; ii < y.size(); ++ii) {
76  arg = y[ii] - A - B * x[ii];
77  sum += arg * arg / ey2[ii];
78  }
79  ChiDOF = sum / ndof;
80  } // LinFit
81 
82 } // namespace trkf
Float_t x
Definition: compare.C:6
Float_t y
Definition: compare.C:6
void LinFit(std::vector< float > &x, std::vector< float > &y, std::vector< float > &ey2, float &Intercept, float &Slope, float &InterceptError, float &SlopeError, float &ChiDOF) const
Definition: LinFitAlg.cxx:16
double weight
Definition: plottest35.C:25
Double_t sum
Definition: plot.C:31