Hi Will,
below you can find the code for fitting an histogram as sum of two other histograms.
I changed a bit your code.
The first change concerns how build the graph, nothing wrong with your method the final result is basically the same, but with my method the final function resemble an histogram.
The TGraphs are now declared as global variable otherwise I was not able to use it inside the function definition.
Other difference, I changed the values you set in h3.
With your value the correct answer was 3 * h1 - 2 * h2 and the program was able to found it.
WIth the current values in h3 the expected answer is 2 * h1+1 * h2
TGraph *gr1 = new TGraph();
TGraph *gr2 = new TGraph();
void RootTalk() {
// Run as > root.exe RootTalk.C
TH1F *h1 = new TH1F("h1", "h1 title", 5, 0, 5);
TH1F *h2 = new TH1F("h2", "h2 title", 5, 0, 5);
TH1F *h3 = new TH1F("h3", "h3 title", 5, 0, 5);
h1->SetBinContent(1,1);
h3->SetBinContent(1,2);//h3->SetBinContent(1,3) this was your previous setting
//2*1+ 1*0=2
h1->SetBinContent(2,2);
h2->SetBinContent(2,1);
h3->SetBinContent(2,5);//h3->SetBinContent(2,4) this was your previous setting
//2*2 + 1*1 = 5
for(int i=1; i <=h1->GetNbinsX(); ++i) {
gr1->SetPoint(gr1->GetN(),h1->GetBinLowEdge(i)+0.001*h1->GetBinWidth(i),h1->GetBinContent(i));
gr1->SetPoint(gr1->GetN(),h1->GetBinLowEdge(i+1)-0.001*h1->GetBinWidth(i),h1->GetBinContent(i));
gr2->SetPoint(gr2->GetN(),h2->GetBinLowEdge(i)+0.001*h2->GetBinWidth(i),h2->GetBinContent(i));
gr2->SetPoint(gr2->GetN(),h2->GetBinLowEdge(i+1)-0.001*h2->GetBinWidth(i),h2->GetBinContent(i));
//gr1->SetPoint(gr1->GetN(),h1->GetBinCenter(i),h1->GetBinContent(i));
//gr2->SetPoint(gr1->GetN(),h2->GetBinCenter(i),h2->GetBinContent(i));
}
TF1 * f_sum=new TF1("f_sum",[&](double* x, double* p){return p[0]*gr1->Eval(x[0]) + p[1]*gr2->Eval(x[0]);},0.,5,2);
f_sum->SetNpx(1000);
h3->Draw("");
h3->Fit("f_sum");
// TF1 *f = new TF1("f", "[0]*gr1+[1]*gr2"); // bad syntax
// h3->Fit("f");
// If successful, the "correct" answer is h3 = 2 * h1 + h2. Can I make a fit to do this?
}
Best,
Stefano