TExcelTAD
Home › Differential Equations › Differential Equations with Python

Differential Equations with Python

Three tools cover almost everything in this course: SymPy for exact solutions, SciPy's solve_ivp for numerical solutions, and NumPy/Matplotlib for tables and pictures. This lesson shows the pattern you will reuse in every later lesson.

Exact solutions with SymPy

Declare the independent variable as a symbol and the unknown as a Function, write the equation with sp.Eq, and call sp.dsolve. Without initial conditions you get the general solution with constants C1, C2, …; with ics= you get the particular solution.

python · try it yourself
import sympy as sp

t = sp.symbols("t")
y = sp.Function("y")
ode = sp.Eq(y(t).diff(t, 2) + 4 * y(t), 0)          # y'' + 4y = 0
print("general:   ", sp.dsolve(ode))
print("particular:", sp.dsolve(ode, ics={y(0): 1, y(t).diff(t).subs(t, 0): 0}))
general:    Eq(y(t), C1*sin(2*t) + C2*cos(2*t))
particular: Eq(y(t), cos(2*t))

A second-order equation needs two conditions: the value y(0)y(0) and the slope y′(0)y'(0). In SymPy the slope condition is written y(t).diff(t).subs(t, 0).

Numerical solutions with solve_ivp

solve_ivp(f, (t0, t1), y0) solves y′=f(t,y)\mathbf{y}' = f(t, \mathbf{y}). It only accepts first-order systems, so a second-order equation is rewritten with y1=yy_1 = y, y2=y′y_2 = y':

y′′+4y=0⟺{y1′=y2y2′=−4y1y'' + 4y = 0 \quad\Longleftrightarrow\quad \begin{cases} y_1' = y_2 \\ y_2' = -4y_1 \end{cases}
python · try it yourself
import numpy as np
from scipy.integrate import solve_ivp

def f(t, Y):
    y1, y2 = Y
    return [y2, -4 * y1]

ts = np.linspace(0, np.pi, 5)
sol = solve_ivp(f, (0, np.pi), [1.0, 0.0], t_eval=ts, rtol=1e-10, atol=1e-12)
for t, y in zip(sol.t, sol.y[0]):
    print(f"t = {t:.4f}  y = {y: .6f}  cos(2t) = {np.cos(2 * t): .6f}")
t = 0.0000  y =  1.000000  cos(2t) =  1.000000
t = 0.7854  y = -0.000000  cos(2t) =  0.000000
t = 1.5708  y = -1.000000  cos(2t) = -1.000000
t = 2.3562  y =  0.000000  cos(2t) = -0.000000
t = 3.1416  y =  1.000000  cos(2t) =  1.000000

Always pass rtol and atol when you compare with an exact answer: the defaults (rtol=1e-3) are only good to about three digits. The method itself is explained in Numerical Methods.

Pictures with Matplotlib

A family of solutions, one curve per initial value, shows the behaviour of the whole equation at a glance:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

t = np.linspace(0, 6, 200)
fig, ax = plt.subplots(figsize=(6, 3.5))
for y0 in (-2, -1, 0, 1, 2, 3):
    ax.plot(t, 1 + (y0 - 1) * np.exp(-t), label=f"y(0) = {y0}")   # solutions of y' = 1 - y
ax.set_xlabel("t"); ax.set_ylabel("y"); ax.set_title("Solutions of y' = 1 - y")
ax.legend(fontsize=7)
print("every curve approaches y = 1")
every curve approaches y = 1

A complete workflow

Solve exactly, solve numerically, compare. The equation y′=t−yy' = t - y, y(0)=1y(0) = 1 is linear (see Linear Equations and the Integrating Factor).

python · try it yourself
import numpy as np
import sympy as sp
from scipy.integrate import solve_ivp

t = sp.symbols("t")
y = sp.Function("y")
exact = sp.dsolve(sp.Eq(y(t).diff(t), t - y(t)), ics={y(0): 1}).rhs
print("exact:", exact)
f_exact = sp.lambdify(t, exact, "numpy")

sol = solve_ivp(lambda t, y: t - y, (0, 3), [1.0], t_eval=[1, 2, 3], rtol=1e-9, atol=1e-12)
print("max error:", f"{np.max(np.abs(sol.y[0] - f_exact(sol.t))):.1e}")
exact: t - 1 + 2*exp(-t)
max error: 2.5e-10

sp.lambdify turns a SymPy expression into a fast NumPy function, which is the bridge between the exact and the numerical world.

In software

  • SymPy's dsolve is a computer algebra system, like Mathematica's DSolve or Maple's dsolve. It recognises equation types (separable, linear, exact, constant coefficients, …) and applies the textbook method.
  • scipy.integrate.solve_ivp (Runge-Kutta 4/5 by default, method="LSODA" or "BDF" for stiff problems), MATLAB's ode45 and Julia's DifferentialEquations.jl are the numerical workhorses of simulation software.
  • Physics engines in games solve Newton's equations with simple fixed-step versions of the same idea (Game Physics).

Exercises

Exercise 1: General solution (code)

Find the general solution of y′=3yy' = 3y with SymPy. How many arbitrary constants does it have, and why?

Answer

y=C1e3ty = C_1e^{3t}: one constant, because the equation is first order.

Solution
python · try it yourself
import sympy as sp
t = sp.symbols("t"); y = sp.Function("y")
print(sp.dsolve(sp.Eq(y(t).diff(t), 3 * y(t))))
Eq(y(t), C1*exp(3*t))

An nnth-order equation has nn constants in its general solution, one for each integration.

Exercise 2: Rewrite as a system

Rewrite y′′+0.5y′+9y=0y'' + 0.5y' + 9y = 0 as a first-order system for y1=yy_1 = y, y2=y′y_2 = y'.

Answer

y1′=y2y_1' = y_2, y2′=−9y1−0.5y2y_2' = -9y_1 - 0.5y_2.

Solution

By definition y1′=y′=y2y_1' = y' = y_2. Solve the equation for the highest derivative: y′′=−9y−0.5y′y'' = -9y - 0.5y', which in the new variables is y2′=−9y1−0.5y2y_2' = -9y_1 - 0.5y_2.

Exercise 3: Numeric check (code)

Solve y′=−2tyy' = -2ty, y(0)=1y(0) = 1 numerically on [0,2][0, 2] and compare y(2)y(2) with the exact solution e−t2e^{-t^2}.

Answer

y(2)=e−4≈0.018316y(2) = e^{-4} \approx 0.018316.

Solution
python · try it yourself
import numpy as np
from scipy.integrate import solve_ivp
sol = solve_ivp(lambda t, y: -2 * t * y, (0, 2), [1.0], rtol=1e-10, atol=1e-12)
print(f"{sol.y[0][-1]:.6f} {np.exp(-4):.6f}")
0.018316 0.018316

Test yourself

What does solve_ivp require as input?

  1. A first-order system y′=f(t,y)\mathbf{y}' = f(t, \mathbf{y}) with an initial vector
  2. Any equation as a string
  3. The exact solution
  4. A second-order equation directly

How many arbitrary constants are in the general solution of a third-order ODE?

  1. 1
  2. 2
  3. 3
  4. It depends on the right-hand side

What does sp.lambdify(t, expr, "numpy") do?

  1. Solves the equation
  2. Turns a SymPy expression into a NumPy-callable function
  3. Plots the expression
  4. Differentiates the expression