Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Fit error function (erf) or similar to data

Tags:

python

scipy

I need to fit a special distribution of data with any available function. The distribution does not really follow a specific theoretical prediction, so I just want to fit any given function without great meaning. I attached an image with a sample distribution and a fifth order polynomial fit to show that this simple approach does not really work.

I know the distribution closely resembles an error function, but I did not manage to fit such a function with scipy...

I hope anyone has either a way to fit an error function to such a distribution, or maybe can suggest a different type of function I could fit to describe this distribution.

Sample data

like image 489
HansSnah Avatar asked Oct 19 '25 15:10

HansSnah


2 Answers

You can fit any function you want:

from scipy.optimize import curve_fit
popt, pcov = curve_fit(func, xdata, ydata)

In case you want some function similar to erf, you can use for example:

def func(z,a,b):
   return a*scipy.special.erf(z)+b

This will find the parameters a,b.

like image 194
Elad Joseph Avatar answered Oct 21 '25 04:10

Elad Joseph


Further fitting parameters might be helpful:

def func(x, a, b, z, f):
return a * scipy.special.erf((x - z)*f) + b

To prevent a runtime error, the number of iterations (default = 800) can be adapted with maxfev:

popt, pcov = curve_fit(func, x, y, maxfev=8000)

(See Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000)

like image 33
Beamey Avatar answered Oct 21 '25 06:10

Beamey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!