# Sum fit functions in PyROOT

Hi,

I’m trying to

• define two TF1 in two different but adjacent ranges (the function is the same, but the parameters will get different values in the two ranges)
• sum the two TF1s
• fit a TH1 with the sum function
``````h = ROOT.TH1F(title1, title2, bins, minb, maxb)
for i in range(0, len(array)):
h.Fill(array[i])
...
ff = ROOT.TF1("ff", "*pow(1 -(1-)*(1./(3-))*(x-)*(x-)*, 1./(1-))", 0, 1, 3)
ff2 = ROOT.TF1("ff2", "*pow(1 -(1-)*(1./(3-))*(x-)*(x-)*, 1./(1-))", 1, 2, 3)
fftotal = ROOT.TF1("fftotal", ff+ff2,0,2,6)
...
h.Fit(fftotal,"M+","",min_fit,max_fit)
``````

However, it seems that I cannot sum the two functions in this way, since I get an error.

``````TypeError: unsupported operand type(s) for +: 'TF1' and 'TF1'
``````

Using the following variation did not work:

``````    fftotal = ROOT.TF1("fftotal", "ff+ff2",0,2,6)
``````

What is the correct way to do so?

Thank you and kind regards,
Lorenzo

@moneta how would you do this in C++? This will give us some hint about how to do it in Python.

Can you try:

``````    fftotal = ROOT.TF1("fftotal", "ff+ff2",0,2,6)
``````

Note the quotes in “ff+ff2”.

I tried using the quotes, but unfortunately I still get an error:

``````input_line_35:2:55: error: use of undeclared identifier 'ff'
Double_t TFormula____id1201809606081465402(){ return {ff}+{ff2} ; }
^
input_line_36:2:55: error: use of undeclared identifier 'ff'
Double_t TFormula____id1201809606081465402(){ return {ff}+{ff2} ; }
^
Error in <prepareMethod>: Can't compile function TFormula____id1201809606081465402 prototype with arguments
Error in <TFormula::InputFormulaIntoCling>: Error compiling formula expression in Cling
Error in <TFormula::ProcessFormula>: "ff" has not been matched in the formula expression
Error in <TFormula::ProcessFormula>: "ff2" has not been matched in the formula expression
Error in <TFormula::ProcessFormula>: Formula "ff+ff2" is invalid !
Error in <Fit>: function fftotal has illegal number of parameters = 0
Traceback (most recent call last):
File "timing_res.py", line 194, in <module>
h10, fit10, chi10, dof10, prob10, binsize10 = histo_ROOT_Q_gaussfit(tarray10, "time distribution", "t10% distribution", "time(ns)", "Counts", 250, 0, 5, "gauss",mean10a-2*rms10a,mean10a+2*rms10a)
fit.SetLineColor(1)
ReferenceError: attempt to access a null-pointer
``````

In C++ it seems to be like this, but this syntax does not seem to work in PyROOT (from ROOT: TF1 Class Reference):

I hope this helps, thanks for your support.
Best,

Lorenzo

Hello,

I translated to Python the C++ example you showed and it does seem to work in PyROOT:

``````import ROOT

fcos = ROOT.TF1("fcos", "*cos(x)", 0., 10.)
fsin = ROOT.TF1("fsin", "*sin(x)", 0., 10.)
fsincos = ROOT.TF1("fsc", "fcos+fsin")
``````

Does this not work with your ROOT installation? What version are you using?

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