Logo ROOT   6.30.04
Reference Guide
 All Namespaces Files Pages
exampleFit3D.C
Go to the documentation of this file.
1 /// \file
2 /// \ingroup tutorial_fit
3 /// \notebook -nodraw
4 /// example of fitting a 3D function
5 /// Typical multidimensional parametric regression where the predictor
6 /// depends on 3 variables
7 ///
8 /// In the case of 1 or 2D one can use the TGraph classes
9 /// but since no TGraph3D class exists this tutorial provide
10 /// an example of fitting 3D points
11 ///
12 /// \macro_output
13 /// \macro_code
14 ///
15 /// \author Lorenzo Moneta
16 
17 
18 #include "TRandom2.h"
19 #include "TF3.h"
20 #include "TError.h"
21 #include "Fit/BinData.h"
22 #include "Fit/Fitter.h"
23 #include "Math/WrappedMultiTF1.h"
24 
25 void exampleFit3D() {
26 
27  const int n = 1000;
28  double x[n], y[n], z[n], v[n];
29  double ev = 0.1;
30 
31  // generate the data
32  TRandom2 r;
33  for (int i = 0; i < n; ++i) {
34  x[i] = r.Uniform(0,10);
35  y[i] = r.Uniform(0,10);
36  z[i] = r.Uniform(0,10);
37  v[i] = sin(x[i] ) + cos(y[i]) + z[i] + r.Gaus(0,ev);
38  }
39 
40  // create a 3d binned data structure
41  ROOT::Fit::BinData data(n,3);
42  double xx[3];
43  for(int i = 0; i < n; ++i) {
44  xx[0] = x[i];
45  xx[1] = y[i];
46  xx[2] = z[i];
47  // add the 3d-data coordinate, the predictor value (v[i]) and its errors
48  data.Add(xx, v[i], ev);
49  }
50 
51  TF3 * f3 = new TF3("f3","[0] * sin(x) + [1] * cos(y) + [2] * z",0,10,0,10,0,10);
52  f3->SetParameters(2,2,2);
53  ROOT::Fit::Fitter fitter;
54  // wrapped the TF1 in a IParamMultiFunction interface for the Fitter class
55  ROOT::Math::WrappedMultiTF1 wf(*f3,3);
56  fitter.SetFunction(wf);
57  //
58  bool ret = fitter.Fit(data);
59  if (ret) {
60  const ROOT::Fit::FitResult & res = fitter.Result();
61  // print result (should be around 1)
62  res.Print(std::cout);
63  // copy all fit result info (values, chi2, etc..) in TF3
64  f3->SetFitResult(res);
65  // test fit p-value (chi2 probability)
66  double prob = res.Prob();
67  if (prob < 1.E-2)
68  Error("exampleFit3D","Bad data fit - fit p-value is %f",prob);
69  else
70  std::cout << "Good fit : p-value = " << prob << std::endl;
71 
72  }
73  else
74  Error("exampleFit3D","3D fit failed");
75 }