Math and Science with Python

Curve Fitting in Python with scipy.optimize.curve_fit

Fit any model function to measured data and get the best parameters with their uncertainties.

  • Intermediate
  • 3 min read
  • 1 runnable example
What you'll learn
  • Writing the model as a Python function
  • Starting guesses with p0
  • Standard errors from the covariance matrix
True values and fitted values
a
  • true 5
  • fit 4.969 +/- 0.072
k
  • true 0.8
  • fit 0.828 +/- 0.030
c
  • 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.

From radio knobs to code
model(t, a, k, c)📻 The radio with three knobs
p0=[4, 1, 0]🎛️ Where the knobs start
curve_fit(model, t, y)🔧 Turn the knobs until the signal is clearest
np.sqrt(np.diag(covariance))📶 How sure you are of each setting
Turn the parameters until the curve matches.
In one sentence

scipy.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

  1. The model's first argument is the x data; the other arguments are the parameters.
  2. p0 gives starting values; for exponentials a sensible guess matters.
  3. np.sqrt(np.diag(covariance)) gives one standard error per parameter.
  4. 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.polyfit is simpler.
  • Many features and prediction as the goal: use a regression model from scikit-learn.

Example code

Open in editor →
main.py
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}")
Get a Run button for this example

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.

  1. Change the function or the data and predict the result before running.
  2. Compare the numerical answer with the exact one from SymPy or a hand calculation.
  3. Plot the result with Matplotlib to see what the numbers mean.
Run in the Python compiler →

Common mistakes

Putting the parameters first

curve_fit passes the x data as the first argument.

Problem
def model(a, k, c, t):
Fix
def model(t, a, k, c):

Using math.exp in the model

math.exp works on one number; the model gets a whole array.

Problem
return a * math.exp(-k * t) + c
Fix
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 challenges

Tools for this lesson