00001 #include "TGraphErrors.h"
00002 #include "TF1.h"
00003 #include "TRandom.h"
00004 #include "TCanvas.h"
00005 #include "TLegend.h"
00006 #include "TMath.h"
00007
00008
00009 void makePoints(Int_t n, Double_t *x, Double_t *y, Double_t *e, Int_t p);
00010
00011 void fitLinear()
00012 {
00013
00014
00015
00016
00017
00018 Int_t n = 40;
00019 Double_t *x = new Double_t[n];
00020 Double_t *y = new Double_t[n];
00021 Double_t *e = new Double_t[n];
00022 TCanvas *myc = new TCanvas("myc",
00023 "Fitting 3 TGraphErrors with linear functions");
00024 myc->SetFillColor(42);
00025 myc->SetGrid();
00026
00027
00028 makePoints(n, x, y, e, 3);
00029 TGraphErrors *gre3 = new TGraphErrors(n, x, y, 0, e);
00030 gre3->Draw("a*");
00031
00032 gre3->Fit("pol3");
00033
00034 TF1 *f3 = gre3->GetFunction("pol3");
00035 f3->SetLineWidth(1);
00036
00037
00038 makePoints(n, x, y, e, 2);
00039 TGraphErrors *gre2=new TGraphErrors(n, x, y, 0, e);
00040 gre2->Draw("*same");
00041 gre2->SetMarkerColor(kBlue);
00042 gre2->SetLineColor(kBlue);
00043
00044
00045
00046
00047
00048
00049
00050 TF1 *f2 = new TF1("f2", "sin(x) ++ sin(2*x)", -2, 2);
00051 gre2->Fit(f2);
00052 f2 = gre2->GetFunction("f2");
00053 f2->SetLineColor(kBlue);
00054 f2->SetLineWidth(1);
00055
00056
00057 makePoints(n, x, y, e, 4);
00058 TGraphErrors *gre4=new TGraphErrors(n, x, y, 0, e);
00059 gre4->Draw("*same");
00060 gre4->SetMarkerColor(kRed);
00061 gre4->SetLineColor(kRed);
00062
00063
00064 gre4->Fit("1 ++ exp(-x)");
00065
00066 TF1 *f4 = gre4->GetFunction("1 ++ exp(-x)");
00067 f4->SetName("f4");
00068 f4->SetLineColor(kRed);
00069 f4->SetLineWidth(1);
00070
00071 TLegend *leg = new TLegend(0.3, 0.7, 0.65, 0.9);
00072 leg->AddEntry(gre3, " -7 + 2*x*x + x*x*x", "p");
00073 leg->AddEntry(gre2, "sin(x) + sin(2*x)", "p");
00074 leg->AddEntry(gre4, "-2 + exp(-x)", "p");
00075 leg->Draw();
00076 leg->SetFillColor(42);
00077
00078
00079 }
00080
00081 void makePoints(Int_t n, Double_t *x, Double_t *y, Double_t *e, Int_t p)
00082 {
00083 Int_t i;
00084 TRandom r;
00085
00086 if (p==2) {
00087 for (i=0; i<n; i++) {
00088 x[i] = r.Uniform(-2, 2);
00089 y[i]=TMath::Sin(x[i]) + TMath::Sin(2*x[i]) + r.Gaus()*0.1;
00090 e[i] = 0.1;
00091 }
00092 }
00093 if (p==3) {
00094 for (i=0; i<n; i++) {
00095 x[i] = r.Uniform(-2, 2);
00096 y[i] = -7 + 2*x[i]*x[i] + x[i]*x[i]*x[i]+ r.Gaus()*0.1;
00097 e[i] = 0.1;
00098 }
00099 }
00100 if (p==4) {
00101 for (i=0; i<n; i++) {
00102 x[i] = r.Uniform(-2, 2);
00103 y[i]=-2 + TMath::Exp(-x[i]) + r.Gaus()*0.1;
00104 e[i] = 0.1;
00105 }
00106 }
00107 }