exampleFit3D.C

Go to the documentation of this file.
00001 // example of fitting a 3D function 
00002 // Typical multidimensional parametric regression where the predictor 
00003 // depends on 3 variables 
00004 // 
00005 // In the case of 1 or 2D one can use the TGraph classes
00006 // but since no TGraph3D class exists this tutorial provide 
00007 // an example of fitting 3D points 
00008 //
00009 // Author: L. Moneta Dec. 2010
00010 
00011 #include "TRandom2.h"
00012 #include "TF3.h"
00013 #include "TError.h"
00014 #include "Fit/BinData.h"
00015 #include "Fit/Fitter.h"
00016 #include "Math/WrappedMultiTF1.h"
00017 
00018 void exampleFit3D() { 
00019    
00020    const int n = 1000; 
00021    double x[n], y[n], z[n], v[n]; 
00022    double ev = 0.1;
00023 
00024    // generate the data
00025    TRandom2 r; 
00026    for (int i = 0; i < n; ++i) { 
00027       x[i] = r.Uniform(0,10);
00028       y[i] = r.Uniform(0,10);
00029       z[i] = r.Uniform(0,10); 
00030       v[i] = sin(x[i] ) + cos(y[i]) + z[i] + r.Gaus(0,ev);         
00031    }
00032 
00033    // create a 3d binned data structure
00034    ROOT::Fit::BinData data(n,3); 
00035    double xx[3];
00036    for(int i = 0; i < n; ++i) {
00037       xx[0] = x[i]; 
00038       xx[1] = y[i]; 
00039       xx[2] = z[i]; 
00040       // add the 3d-data coordinate, the predictor value (v[i])  and its errors
00041       data.Add(xx, v[i], ev); 
00042    }
00043 
00044    TF3 * f3 = new TF3("f3","[0] * sin(x) + [1] * cos(y) + [2] * z",0,10,0,10,0,10);
00045    f3->SetParameters(2,2,2);
00046    ROOT::Fit::Fitter fitter;
00047    // wrapped the TF1 in a IParamMultiFunction interface for teh Fitter class
00048    ROOT::Math::WrappedMultiTF1 wf(*f3,3);
00049    fitter.SetFunction(wf); 
00050    //
00051    bool ret = fitter.Fit(data); 
00052    if (ret) { 
00053       const ROOT::Fit::FitResult & res = fitter.Result(); 
00054       // print result (should be around 1) 
00055       res.Print(std::cout);
00056       // copy all fit result info (values, chi2, etc..) in TF3
00057       f3->SetFitResult(res);
00058       // test fit p-value (chi2 probability)
00059       double prob = res.Prob();
00060       if (prob < 1.E-2) 
00061          Error("exampleFit3D","Bad data fit - fit p-value is %f",prob);
00062       else
00063          std::cout << "Good fit : p-value  = " << prob << std::endl;
00064 
00065    }
00066    else 
00067       Error("exampleFit3D","3D fit failed");
00068 } 

Generated on Tue Jul 5 15:44:06 2011 for ROOT_528-00b_version by  doxygen 1.5.1