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 dydx=y.

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

y(x)+ddxy(x)

You can solve an ODE by using the dsolve command.

1
2
solution = dsolve( ode )
solution

y(x)=C1ex

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

5=C1e3

1
solve( with_inits )

[5e3]

To substitute C1=5e3 into the solution, note that C1 is written as var('C1').

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

y(x)=5exe3

Content last modified on 24 July 2023.

See a problem? Tell us or edit the source.

Contributed by Nathan Carter (ncarter@bentley.edu)