Curve Fitting in Python with scipy.optimize.curve_fit
Fit any model function to measured data and get the best parameters with their uncertainties.
- Writing the model as a Python function
- Starting guesses with p0
- Standard errors from the covariance matrix
- true 5
- fit 4.969 +/- 0.072
- true 0.8
- fit 0.828 +/- 0.030
- true 1
- fit 1.042 +/- 0.045
Find the parameters that match the data
The problem
Lab data rarely lies exactly on a curve: a cooling cup of tea, a charging capacitor or radioactive decay all come with noise. You need the parameters of the model, such as the decay rate, and how certain they are.
Think of it like this
Curve fitting is like adjusting the knobs on a radio until the signal is clearest. Each knob is one parameter of the model, and curve_fit turns them until the curve sits as close to the data points as possible.
model(t, a, k, c)📻 The radio with three knobsp0=[4, 1, 0]🎛️ Where the knobs startcurve_fit(model, t, y)🔧 Turn the knobs until the signal is clearestnp.sqrt(np.diag(covariance))📶 How sure you are of each settingscipy.optimize.curve_fit(f, xdata, ydata) finds the parameters of the model f that minimise the squared differences to the data, and returns them with their covariance matrix.
Key points
- The model's first argument is the x data; the other arguments are the parameters.
p0gives starting values; for exponentials a sensible guess matters.np.sqrt(np.diag(covariance))gives one standard error per parameter.model(6, *params)uses the fitted parameters to predict new values.
When should you use it?
- Fitting lab measurements in physics, chemistry and biology.
- Finding a decay rate, half-life or growth rate.
- Calibration curves for sensors.
When not to use it
- A straight line or polynomial:
np.polyfitis simpler. - Many features and prediction as the goal: use a regression model from scikit-learn.
Example code
import numpy as np
from scipy.optimize import curve_fit
# Model: exponential decay y = a * exp(-k * t) + c
def model(t, a, k, c):
return a * np.exp(-k * t) + c
# Fake measurements: true a=5, k=0.8, c=1 plus some noise
rng = np.random.default_rng(42)
t = np.linspace(0, 5, 20)
y = model(t, 5, 0.8, 1) + rng.normal(0, 0.1, t.size)
# p0 is the starting guess for a, k, c
params, covariance = curve_fit(model, t, y, p0=[4, 1, 0])
errors = np.sqrt(np.diag(covariance)) # standard errors
for name, value, err in zip(["a", "k", "c"], params, errors):
print(f"{name} = {value:.3f} +/- {err:.3f}")
# Use the fitted model to predict
print(f"Predicted y at t = 6: {model(6, *params):.3f}")
Result of running the code
a = 4.969 +/- 0.072
k = 0.828 +/- 0.030
c = 1.042 +/- 0.045
Predicted y at t = 6: 1.076
Code explanation
model() is the exponential decay a * exp(-k * t) + c; its first argument must be the x values and the rest are the parameters to fit. The data y is made from a = 5, k = 0.8, c = 1 plus seeded random noise, so the fit can be compared with the true values. curve_fit returns params and a covariance matrix, and the square root of its diagonal gives the standard errors: a = 4.969 +/- 0.072 is close to 5. p0 is the starting guess, and model(6, *params) uses the fitted values to predict.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the function or the data and predict the result before running.
- Compare the numerical answer with the exact one from SymPy or a hand calculation.
- Plot the result with Matplotlib to see what the numbers mean.
Common mistakes
Putting the parameters first
curve_fit passes the x data as the first argument.
def model(a, k, c, t):
def model(t, a, k, c):
Using math.exp in the model
math.exp works on one number; the model gets a whole array.
return a * math.exp(-k * t) + c
return a * np.exp(-k * t) + c
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
All challengesTools for this lesson
- Linear Regression in Python with scikit-learnFit a straight line with sklearn LinearRegression, read the slope and intercept, measure R^2 and MAE, and predict new values.
- Graph Plotter Online: Plot Points and FunctionsPlot points, a pasted table or functions like sin(x) online and download the graph as a PNG. Free graph maker that also gives you the Python Matplotlib code.
- How to Plot a Graph in Python Online (Matplotlib Examples)Plot a graph in Python online with Matplotlib: lines, functions like sin(x), data from a CSV, bar and pie charts. Run each example in your browser.