Note that you do not need to explicitly write out the input names - np.linspace(-5, 5, 100) is equally valid, but for the purposes of this article, it makes things easier to follow.įor our dummy data set, we will set both the values of a and b to 0.5. Num - the number of points to split the interval up into (default is 50 ) Stop - ending value of our sequence (will include this value unless you provide the extra argument endpoint=False ) # Generate dummy dataset x_dummy = np.linspace(start=5, stop=15, num=50) To generate a set of points for our x values that are evenly distributed over a specified interval, we can use the np.linspace function. We will start by generating a “dummy” dataset to fit with this function. # Function to calculate the exponential with constants a and b def exponential(x, a, b): return a*np.exp(b*x) Let’s say we have a general exponential function of the following form, and we know this expression fits our data (where a and b are constants we will fit):įirst, we must define the exponential function as shown above so curve_fit can use it to do the fitting. In this case, we are only using one specific function from the scipy package, so we can directly import just curve_fit. To use the curve_fit function we use the following import statement: # Import curve fitting package from scipy from scipy.optimize import curve_fit I will go through three types of common non-linear fittings: (1) exponential, (2) power-law, and (3) a Gaussian peak. The basics of plotting data in Python for scientific publications can be found in my previous article here.
This short article will serve as a guide on how to fit a set of points to a known model equation, which we will do using the _fit function.
In addition to plotting data points from our experiments, we must often fit them to a theoretical model to extract important parameters.