Multiplying TH1 by constant

ROOT Version: ROOT/6.06.08/x86_64-slc6-gcc49-opt

Hello,
I’m having a problem filling some histograms in ROOT, more specifically I have a histogram say h1 that I load from a root file, I now want to fill a new histogram with the old multiplied by some factor onto each bin. I do this in python, but the new histogram is empty except for one bin. I have tried t by doing it in a loop:

hnew = ROOT.TH1D(“hnew”,"",100,-1,1)
for i in range(h1.GetXaxis().GetNbins()):
temp = k * h1.GetBinContent(i)
hnew.Fill(temp)

I also found the multiply function, however I’m not quite sure how to use it via python.

  • Thanks!

I think you have some logic mistakes. You should do some like (I write in in C++):

auto hnew = new TH1D(“hnew”,"",100,-1.,1.);
for (int i = 1; i<=h1->GetXaxis()->GetNbins(), i++) {
   temp = k * h1->GetBinContent(i);
   hnew->SetBinContent(i, temp);
}

If you do not need the old histogram afterwards, you could just scale it:

h1.Scale(k)

Or, if you need it, and the old and new histograms have the same binning, and the new one is indeed empty, you could do

hnew.Add(h1, k)

No need to write this yourself.

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