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

## Task

Differential equations are equations that contain differentials like $dy$ and $dx$, often in the form $\frac{dy}{dx}$. 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 $\frac{dy}{dx}$ 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.

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

Letâ€™s now write a very simple differential equation, $\frac{dy}{dx}=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 $\frac{dy}{dx}-y=0$, and we will use just the left-hand side to express our ODE.

1
2

ode = dydx - y
ode

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

Content last modified on 24 July 2023.

See a problem? Tell us or edit the source.

Contributed by Nathan Carter (ncarter@bentley.edu)