fitCircle.C

Go to the documentation of this file.
00001 //Generate points distributed with some errors around a circle
00002 //Fit a circle through the points and draw 
00003 //To run the script, do, eg
00004 //   root > .x fitCircle.C   (10000 points by default)
00005 //   root > .x fitCircle.C(100);  (with only 100 points
00006 //   root > .x fitCircle.C(100000);  with ACLIC
00007 //
00008 //Author: Rene Brun
00009 
00010 #include "TCanvas.h"
00011 #include "TRandom3.h"
00012 #include "TGraph.h"
00013 #include "TMath.h"
00014 #include "TArc.h"
00015 #include "TVirtualFitter.h"
00016 
00017 TGraph *gr;
00018 
00019 //____________________________________________________________________
00020 void myfcn(Int_t &, Double_t *, Double_t &f, Double_t *par, Int_t) {
00021    //minimisation function computing the sum of squares of residuals
00022    Int_t np = gr->GetN();
00023    f = 0;
00024    Double_t *x = gr->GetX();
00025    Double_t *y = gr->GetY();
00026    for (Int_t i=0;i<np;i++) {
00027       Double_t u = x[i] - par[0];
00028       Double_t v = y[i] - par[1];
00029       Double_t dr = par[2] - TMath::Sqrt(u*u+v*v);
00030       f += dr*dr;
00031    }
00032 }
00033 
00034 //____________________________________________________________________
00035 void fitCircle(Int_t n=10000) {
00036    //generates n points around a circle and fit them
00037    TCanvas *c1 = new TCanvas("c1","c1",600,600);
00038    c1->SetGrid();
00039    gr = new TGraph(n);
00040    if (n> 999) gr->SetMarkerStyle(1);
00041    else        gr->SetMarkerStyle(3);
00042    TRandom3 r;
00043    Double_t x,y;
00044    for (Int_t i=0;i<n;i++) {
00045       r.Circle(x,y,r.Gaus(4,0.3));
00046       gr->SetPoint(i,x,y);
00047    }
00048    c1->DrawFrame(-5,-5,5,5);
00049    gr->Draw("p");
00050    
00051    //Fit a circle to the graph points
00052    TVirtualFitter::SetDefaultFitter("Minuit");  //default is Minuit
00053    TVirtualFitter *fitter = TVirtualFitter::Fitter(0, 3);
00054    fitter->SetFCN(myfcn);
00055 
00056    fitter->SetParameter(0, "x0",   0, 0.1, 0,0);
00057    fitter->SetParameter(1, "y0",   0, 0.1, 0,0);
00058    fitter->SetParameter(2, "R",    1, 0.1, 0,0);
00059 
00060    Double_t arglist[1] = {0};
00061    fitter->ExecuteCommand("MIGRAD", arglist, 0);
00062 
00063    //Draw the circle on top of the points
00064    TArc *arc = new TArc(fitter->GetParameter(0),
00065       fitter->GetParameter(1),fitter->GetParameter(2));
00066    arc->SetLineColor(kRed);
00067    arc->SetLineWidth(4);
00068    arc->Draw();
00069 }

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