Skip to main content

Section 13.3 Fitting a curve to data in Python

In this section, we will use the scipy.optimize.curve_fit function to fit a curve to data. In the example below, we define a function func(Rpot, Vin, Rfix) where this is the functional form that scipy.optimize.curve_fit is going to apply when fitting our data. In this function that we define, the first argument (Rpot in our case) is the independent variable. The other arguments (Vin, Rfix) are the fitting parameters. We’ve defined our function assuming that our data describes a voltage divider where
\begin{equation*} \text{func}(R_\text{pot}) = V_\text{out} = \frac{R_\text{pot}}{R_\text{fixed}+R_\text{pot}}\text{.} \end{equation*}
The actual curve fitting is then performed with the opt.curve_fit command which takes as arguments the function name (func), and the xdata and ydata. The outputs that we get from the curve_fit function are stored in param and param_cov which represent an array with our fit parameters and a 2D array containing the approximate covariance matrix. For our purposes, you just need to know that np.sqrt(np.diag(pcov)) approximates the standard deviation on the fit parameters. See the official documentation for scipy.optimize.curve_fit for further details. Here, we provide an example. When generating the synthetic ‘data’ below, we assumed that \(V_\text{in}=5.0\text{V}\) and \(R_\text{fixed}=5\text{k}\Omega\text{.}\)