Math and Science with Python

Derivatives in Python with SymPy diff

Differentiate any expression exactly with sympy.diff, or estimate a slope numerically with a central difference.

  • Intermédiaire
  • 3 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • First and second derivatives with sp.diff
  • Evaluating a derivative with subs
  • A numerical derivative with a central difference
Differentiating x**3 + 2*x**2 - 5*x
  1. 1x**3 + 2*x**2 - 5*xf(x)
  2. 23*x**2 + 4*x - 5f'(x)
  3. 315f'(2)

The slope at every point

Découvrez Derivatives in Python with SymPy avec un exemple pratique modifiable et exécutable en ligne.

Points clés

  1. x = sp.symbols("x") creates a symbol that SymPy can differentiate.
  2. sp.diff(f, x) is the first derivative and sp.diff(f, x, 2) the second.
  3. df.subs(x, 2) substitutes a value and returns the exact result, 15.
  4. The central difference (g(at + h) - g(at - h)) / (2 * h) works for any Python function.

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 math
import sympy as sp

# Exact derivatives with SymPy
x = sp.symbols("x")
f = x**3 + 2*x**2 - 5*x
df = sp.diff(f, x)          # first derivative
d2f = sp.diff(f, x, 2)      # second derivative
print("f(x)   =", f)
print("f'(x)  =", df)
print("f''(x) =", d2f)
print("f'(2)  =", df.subs(x, 2))
print("d/dx sin(x)*exp(x) =", sp.diff(sp.sin(x) * sp.exp(x), x))

# Numerical derivative with a central difference
def derivative(g, at, h=1e-5):
    return (g(at + h) - g(at - h)) / (2 * h)

g = lambda t: t**3 + 2*t**2 - 5*t
print(f"Numerical f'(2) = {derivative(g, 2):.6f}")
print(f"Numerical sin'(0) = {derivative(math.sin, 0):.6f}")
Obtenir un bouton Run pour cet exemple

Résultat de l’exécution

f(x)   = x**3 + 2*x**2 - 5*x
f'(x)  = 3*x**2 + 4*x - 5
f''(x) = 2*(3*x + 2)
f'(2)  = 15
d/dx sin(x)*exp(x) = exp(x)*sin(x) + exp(x)*cos(x)
Numerical f'(2) = 15.000000
Numerical sin'(0) = 1.000000

Explication du code

Cet exemple montre Derivatives in Python with SymPy 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