using namespace ROOT; using namespace RooFit; void fit() { RooRealVar x("x", "", 0, 6); RooRealVar weight("weight", "", 0, 100); RooArgSet argSet = RooArgSet(x, weight); RooDataSet ds("ds", "", argSet, "weight"); TF1 f("f", "exp(-x/10)", 0, 6); TRandom3 r3; r3.SetSeed(UShort_t(-1)); TH1D* h = new TH1D("h", "", 60, 0, 6); TH1D* hweight = new TH1D("hweight", "", 60, 0, 6); for(int i=0; i<20000; ++i) { const double temp = r3.Gaus(3, 1); const double threshold = f.Eval(temp); // const double threshold = 1; const double chance = r3.Uniform(0., 1.); if (chance > threshold) continue; else { x.setVal(temp); weight.setVal(1./threshold); ds.add(argSet); h->Fill(temp); hweight->Fill(temp, 1./threshold); } } TCanvas* c2 = new TCanvas("c2", "", 800, 600); c2->cd(); RooRealVar mean("mean", "mean", 3, 2, 4); RooRealVar sigma("sigma", "sigma", 1, 0.01, 2); RooGaussian gaus("gaus", "", x, mean, sigma); RooRealVar nsig("nsig", "yields", 0, 50000); RooExtendPdf extpdf("extpdf", "", gaus, nsig); // extpdf.fitTo(ds, Extended(kTRUE), SumW2Error(kTRUE)); extpdf.fitTo(ds, Extended(kTRUE), AsymptoticError(kTRUE)); RooPlot* frame = x.frame(); ds.plotOn(frame, Binning(60)); extpdf.plotOn(frame, Name("extpdf_curve")); auto extpdf_curve = frame->getCurve("extpdf_curve"); extpdf.paramOn(frame); c2->cd(); frame->Draw(); frame->GetYaxis()->SetRangeUser(0, 1100); // h->SetLineColor(kRed); h->Draw("SAME"); TF1* fgaus = new TF1("fgaus", "gausn", 0, 6); hweight->Fit(fgaus, "WL0"); hweight->SetLineColor(kRed); hweight->Draw("SAME"); fgaus->Draw("SAME"); TLegend* leg = new TLegend(0.1, 0.75, 0.4, 0.89); leg->SetFillStyle(0); leg->SetLineWidth(0); leg->AddEntry(extpdf_curve, "RooFit", "l"); leg->AddEntry(fgaus, "TF1", "l"); leg->Draw(); c2->Print("c2.png"); }