Link Search Menu Expand Document (external link)

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

See all solutions.

Task

Differential equations are equations that contain differentials like dy and dx, often in the form dydx. How can we write them using software?

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

The following code tells SymPy that x is a variable and that y is a function of x. It then expresses dydx as the derivative of y with respect to x.

1
2
3
4
var( 'x' )                 # Let x be a variable.
y = Function('y')(x)       # Literally, y is a function, named y, based on x.
dydx = Derivative( y, x )  # How to write dy/dx.
dydx                       # Let's see how SymPy displays dy/dx.

ddxy(x)

Let’s now write a very simple differential equation, dydx=y.

As with how to do implicit differentiation, SymPy expects us to move everything to the left hand side of the equation. In this case, that makes the equation dydxy=0, and we will use just the left-hand side to express our ODE.

1
2
ode = dydx - y
ode

y(x)+ddxy(x)

Content last modified on 24 July 2023.

See a problem? Tell us or edit the source.

Contributed by Nathan Carter (ncarter@bentley.edu)