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.
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 and the slope . 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 . It only accepts first-order systems, so a second-order equation is rewritten with , :
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:
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 , is linear (see Linear Equations and the Integrating Factor).
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
dsolveis a computer algebra system, like Mathematica'sDSolveor Maple'sdsolve. 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'sode45and 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 with SymPy. How many arbitrary constants does it have, and why?
Answer
: one constant, because the equation is first order.
Solution
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 th-order equation has constants in its general solution, one for each integration.
Exercise 2: Rewrite as a system
Rewrite as a first-order system for , .
Answer
, .
Solution
By definition . Solve the equation for the highest derivative: , which in the new variables is .
Exercise 3: Numeric check (code)
Solve , numerically on and compare with the exact solution .
Answer
.
Solution
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?
- A first-order system with an initial vector
- Any equation as a string
- The exact solution
- A second-order equation directly
How many arbitrary constants are in the general solution of a third-order ODE?
- 1
- 2
- 3
- It depends on the right-hand side
What does sp.lambdify(t, expr, "numpy") do?
- Solves the equation
- Turns a SymPy expression into a NumPy-callable function
- Plots the expression
- Differentiates the expression