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.

  • Intermédiaire
  • 3 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • 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

Découvrez Curve Fitting in Python with SciPy curve_fit avec un exemple pratique modifiable et exécutable en ligne.

Points clés

  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.

Quand l’utiliser ?

  • Solve equations, integrals and differential equations in a few lines.
  • Fit models to measured data and analyse signals in science and engineering classes.
  • Check homework answers numerically and see where a hand calculation went wrong.

Code d’exemple

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}")
Obtenir un bouton Run pour cet exemple

Résultat de l’exécution

a = 4.969 +/- 0.072
k = 0.828 +/- 0.030
c = 1.042 +/- 0.045
Predicted y at t = 6: 1.076

Explication du code

Cet exemple montre Curve Fitting in Python with SciPy curve_fit en pratique. Modifiez les valeurs d’entrée et relancez le code pour voir ce qui change.

Modifiez les valeurs et exécutez le programme avec le compilateur Python en ligne CodeUtility, sans installation locale.

Exercices d’approfondissement

Essayez de modifier le code en suivant les pistes ci-dessous. Changer le code et observer le résultat vous fera bien mieux comprendre la leçon que la simple lecture.

  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.
Exécuter dans le compilateur Python →

Leçon terminée ?

Marquez-la comme apprise pour suivre votre progression.

S'entraîner avec un défi

Utilisez le contenu de cette leçon pour résoudre un vrai problème. Chaque défi s'exécute dans le navigateur, avec des tests instantanés et une revue par l'IA.

Tous les défis

Outils pour cette leçon