Loop over the x axis of an histo and apply a user defined function

Good Morning,

I am trying to define two functions, f and g, that contain the log of the x axis of an histogram I called h1, the code I came up with is the following:

Double_t x1 = 0.0;
Double_t x2 = 1087.895;
Double_t x3 = 4018.081152;
Int_t xbins = h1->GetNbinsX();

for (Int_t b=0; b<xbins; b++){
  TF1 *g = new TF1 ("g", "-29.7 + 19.3*log([b]) - 3.1*(log([b])*log([b])) +0.1*(log([b])*log([b])*log([b)))", x1, x2);

  TF1 *f = new TF1("f", "-1.9 + 4.1*log([b]) - 0.3*(log([b])*log([b]))", x2, x3);

  TCanvas *can1 = new TCanvas();
  can1->Divide(1,2);
  can1->cd(1);
  g[b]->Draw();

  can1->cd(2);
  f[b]->Draw();

}

but this doesn’t work at all…could someone explain me why and what can I do to fix it?

thank you very much

errata corrige TF1 *g = (…); and TF1 *f = (…)

Hi,
in your loop over the bins
for (Int_t b=0; b<xbins; b++) {...}
the b is a bin number, not a bin content. Are you sure you want the bin number to enter your functions f and g?

Hi,
yes you are right, I’d like the bin content…how should I correct it?

thank you

Hi,
Instead of log(b) you should use log(h1->GetBinContents(b)).
Moreover if you put the declaration of g and f in the loop you will redefine g and f.

If you want two analytical function there is no need of a loop instead of b, you should use x in the TF1 declaration, and you don’t need any loop.

Cheers,
Stefano

It’s GetBinContent(), not GetBinContents().

Thank you both for your help!
I removed the for loop because, Stefano you were right…I don’t need it. Now it does compile but it is impossible to draw the functions because it says that the bin content is unknown, this is impossible because I plot h1 properly and perform a series of operations correctly.

cheers
Lex

Basically, I generate an empty canvas and I read “error Formula is invalid and not ready to execute XbinContent is unknown”.

where
Int_t xbins = h1->GetNbinsX();
Double_t XbinContent = h1->GetBinContent(xbins);

and I wrote log(XbinContent) in the functions f and g

cheers
Lex

You don’t need to write XbinContent as log argument, you have to put an x as log argument and then will draw it without problems.
Otherwise you will need a TGraph

Cheers,
Stefano

In the TGraph case you need the loop

TGraph *f=new TGraph();
TGraph *g=new TGraph();

Int_t xbins = h1->GetNbinsX();

for (Int_t b=0; b<xbins; b++){
f->SetPoint(b,h1->GetBinCenter(b), 1.9 + 4.1*log(h1->GetBinContent(b)) - 0.3*(h1->GetBinContent(b))*log(h1->GetBinContent(b)))   );

...same for g...

}

then draw the two TGgraph

Stefano

I suppose this loop should go as

for (Int_t b=1; b<=xbins; b++){...}

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.