# Changing fitting algorithm and maximum number of iterations

Hi all,

I am not very familiar with ROOT (or PyROOT), and I am running my head against a wall here.

I am trying to fit a function (with five parameters) to some data points using TGraph.Fit(). Most of the time this works just fine, but the parameter space seems to be hard to navigate, as the chi^2 of the best fit varies from ~150 to 10^20, depending on my (pseudo-random) initial guesses.

I therefore want to try another fitting algorithm (e.g. BFGS), and maybe set the maximum number of iterations higher, to (hopefully) get some better fits. I know this is possible using the MinimizerOptions class, but any custom settings here seems to be overwritten by TGraph.Fit(). How can I avoid this?

Hi,

if you provide a script with your progress so far, I might be able to figure out what is going on, but this isn’t my expertise at all and you will get better answers in the “Stat and Math Tools” forum.

Cheers,
Wim

Hi Wim,

Well, I think it might just be easier to rephrase the question, as I’m really not sure what to do. Basically, I’m using a TGraph() object and fill it with data points. In pseudo-ish code:

```g = TGraph() for i in range(N): g.SetPoint(i, x[i], y[i])```
I make a TF1()-function and fit to it (again, in pseudo-ish code):

This works perfectly. Now, how do I change the maximum number of iterations? I have tried both of the following:

```gMinuit.SetMaxIterations(10000) ROOT.Math.MinimizerOptions.SetDefaultMaxIterations(10000) ```
but without any luck. I seems that Fit() defaults the MaxIterations on every run. Any ideas how to avoid this?

If this isn’t your area, I will just ask in that other forum. Thanks a lot!

Hi,

well, if I can’t actually run the code, I can’t try anything out …

But what I think is needed, is to get the underlying fitter object that was used by g.Fit(), which may be gMinuit but likely not, and I think you get that by doing:`fitter = TVirtualFitter.Fitter(g)`after which you can do:`fitter.SetMaxIterations(10000)`
As for setting the default max iterations, I think that call might work if the fitter object isn’t created yet, but has no effect on existing fitters (i.e. after the Fit() call). And no, this isn’t my expertise …

Cheers,
Wim

Many thanks for your reply! I will try your suggestion about using TVirtualFitter, which I hadn’t really come across before. But looking around the forum, it does indeed seem to be the way to go.

I will give it a shot, and ask in the Stat and Math Tool forum if I keep being stuck.

Again, thank you very much for your help!