In this post, I show a sample code along with a YouTube tutorial that can be used to fit a set of data-points using a non-linear fitting function with multiple fitting parameters.

I believe the code is pretty much self explanatory, and the YouTube video goes through all the details, so I won’t write much.

Enjoyyy

### CODE:

import matplotlib.pyplot as plt from scipy.optimize import curve_fit import numpy as np #Fitting function def func(x, a, b): return a*np.exp(b*x) #return a*x+b #Experimental x and y data points xData = np.array([1, 2, 3, 4, 5]) yData = np.array([1, 9, 50, 300, 1500]) #Plot experimental data points plt.plot(xData, yData, 'bo', label='experimental-data') # Initial guess for the parameters initialGuess = [1.0,1.0] #Perform the curve-fit popt, pcov = curve_fit(func, xData, yData, initialGuess) print(popt) #x values for the fitted function xFit = np.arange(0.0, 5.0, 0.01) #Plot the fitted function plt.plot(xFit, func(xFit, *popt), 'r', label='fit params: a=%5.3f, b=%5.3f' % tuple(popt)) plt.xlabel('x') plt.ylabel('y') plt.legend() plt.show()

### YouTube Tutorial

### SciPy Documentation

https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html

Ph.D. researcher at Friedrich-Schiller University Jena, Germany. I’m a physicist specializing in computational material science. I write efficient codes for simulating light-matter interactions at atomic scales. I like to develop Physics, DFT, and Machine Learning related apps and software from time to time. Can code in most of the popular languages. I like to share my knowledge in Physics and applications using this Blog and a YouTube channel.

how to do it for a function:(a*np.exp(b*x)+c) on data obtained from csv file?

I want to learn step by step , could you help me? i very want to learn THX

Thank you for your tutorial. Its a great help.

hi, can python do fitting for nonlinear curve? Let say have datas (x,y),and from there got the equation. the equation have 3 known variables (2 varied, 1 fixed) and 1 unknown variable. from the fitting curve, the report will gv value of the unknown variable. is pyhton can do that?