import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from scipy.integrate import quad
from scipy.optimize import fsolve
from scipy.interpolate import interp1d
from scipy.optimize import curve_fit
Curve fitting is used to represent a set of data by a model function.
Recall the procedure in Excel
Python
polyfit
for polynomial fits (including linear)curve_fit
for general curve fitsp = np.polyfit(xg, yg, polynomial_order)
np.polyval(p, xw)
polyfit
polyval
xg
data.xg = np.array([0., 1., 2., 3., 4., 5.]) # given x data
yg = np.array([0, 0.8, 0.9, 0.1, -0.8, -1.0]) # given y data
xg = np.array([2, 3, 4, 5, 6, 7, 8])
yg = np.array([1, 2, 1, 2, 1, 2, 1])
We can fit a general function f(x; a, b, c) where f is a function of x with parameters a, b, c that we want to optimize for a set of given data.
Use curve_fit
available from from scipy.optimize import curve_fit
params, extras = curve_fit(f, xg, yg)
Fit the following function to the given data $$f(x) = a\exp(-bx) + c$$
#-------- Set some given data (normally, this is already available)
xg = np.linspace(0,4,100)
yg = 2.5*np.exp(-1.3*xg)+0.5 + 0.2*np.random.normal(size=len(xg))
plt.plot(xg,yg,'.', markersize=5.0);
curve_fit
function call?help(curve_fit)
for details on this and other options.