Link Search Menu Expand Document (external link)

How to solve an ordinary differential equation (in Python, using SymPy)

See all solutions.

Task

Elsewhere we’ve seen how to write an ordinary differential equation. Once one is written, how can we ask software to solve it? And since ODEs often come with initial conditions that impact the solution, how can we include those as well?

Solution

This answer assumes you have imported SymPy as follows.

1
2
from sympy import *                   # load all math functions
init_printing( use_latex='mathjax' )  # use pretty math output

Let’s re-use here the code from how to write an ordinary differential equation, to write $\frac{dy}{dx}=y$.

1
2
3
4
5
var( 'x' )
y = Function('y')(x)
dydx = Derivative( y, x )
ode = dydx - y
ode

$\displaystyle - y{\left(x \right)} + \frac{d}{d x} y{\left(x \right)}$

You can solve an ODE by using the dsolve command.

1
2
solution = dsolve( ode )
solution

$\displaystyle y{\left(x \right)} = C_{1} e^{x}$

If there are initial conditions that need to be substituted in for $x$ and $y$, it is crucial to substitute for $y$ first and then $x$. Let’s assume we have the initial condition $(3,5)$. We might proceed as follows.

1
2
with_inits = solution.subs( y, 5 ).subs( x, 3 )
with_inits

$\displaystyle 5 = C_{1} e^{3}$

1
solve( with_inits )

$\displaystyle \left[ \frac{5}{e^{3}}\right]$

To substitute $C_1=\frac{5}{e^3}$ into the solution, note that $C_1$ is written as var('C1').

1
solution.subs( var('C1'), 5/E**3 )

$\displaystyle y{\left(x \right)} = \frac{5 e^{x}}{e^{3}}$

Content last modified on 24 July 2023.

See a problem? Tell us or edit the source.

Contributed by Nathan Carter (ncarter@bentley.edu)