3

I have a set of data points which, according to the model I want to implement, could be modelled with a certain curve (in this case, a product between an exponential and a complementary error function).

For fitting these data into such a curve, I tried:

import numpy as np
from scipy.optimize import curve_fit
from scipy import special

x_fit = np.linspace(0,1,1000)
def fitted_function(x_fit, c, d, S):
    return c*np.exp(((S*d/2)**2)-x_fit*d)*special.erfc(S*d/2-x_fit/S)
FitParameters, FitCovariance = curve_fit(fitted_function, x_data, y_data, maxfev = 100000)

It does not give me any particular error, but the result of the fitting is evidently wrong. I strongly suspect that it has to do with the the part x_fit/S, where the fitting parameter S appears as a denominator.

For example, I encounter the same problem while fitting a simple exponential: if I define the fitting curve with

    return a*np.exp(-x_fit/b)

with a, b fitting parameters; since the fitting parameter b appears as a denominator, I find the same problem (i.e. the resulting fitted curve is a horizontal line for some reason). For the case of a simple exponential I can simple bypass this by doing

    return a*np.exp(-b*x_fit)

so that b is not a denominator anymore and the fitted curve is really an exponential curve. For my current case, instead, I cannot do this since S appears ad a numerator and a denominator in different part of the expression. Any ideas? Thank you in advance!

  • 3
    Have you tried giving reasonable initial guesses for the parameters (at least the correct order of magnitude) to `curve_fit`, using the `p0` argument? – rtoijala Jul 01 '19 at 10:35
  • No, I didn't, but effectively it works now! Thank you! – Antonello Zito Jul 01 '19 at 10:44
  • a non linear fitting as in your case is really sensitive to the initial guess, check [link](https://stackoverflow.com/questions/3433486/how-to-do-exponential-and-logarithmic-curve-fitting-in-python-i-found-only-poly) – Matteo Peluso Jul 01 '19 at 15:54
  • Possible duplicate of [How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting](https://stackoverflow.com/questions/3433486/how-to-do-exponential-and-logarithmic-curve-fitting-in-python-i-found-only-poly) – Matteo Peluso Jul 01 '19 at 15:55

0 Answers0