How to solve an ordinary differential equation (in Python, using SymPy)
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
1
2
3
4
5
var( 'x' )
y = Function('y')(x)
dydx = Derivative( y, x )
ode = dydx - y
ode
You can solve an ODE by using the dsolve
command.
1
2
solution = dsolve( ode )
solution
If there are initial conditions that need to be substituted in for
1
2
with_inits = solution.subs( y, 5 ).subs( x, 3 )
with_inits
1
solve( with_inits )
To substitute var('C1')
.
1
solution.subs( var('C1'), 5/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)