 Introduction

This presentation outlines how to use python as a an ordinary differential equation (ode) solver. Python produces the solution numerically using the SciPy ode engine (integrate module). The solution is therefore not in analytic form but is as if the analytic function was computed for each time step. We will use a series RC circuit for our example.

Step 1

Get ode and rearrange in the following form:

x'=f(x)

For our RC circuit example from:

V=RCVc'+Vc

we have:

Vc'=(V-Vc)/RC

Step 2

Implement a python function that returns the right hand side of the rearranged equation, ie f(x)

For our example we have:

def capVolts(Vc,t):

V = 12

R = 0.5

C = 1

return (V-Vc)/(R*C) #f(x)

Step 3

Define the time steps for the solution.

time = linspace(0.0,5.0,1000)

Call the integrate function to obtain the solution.

y = integrate.odeint(capVolts,0,time)

Step 4

Plot the solution:

plot(time,y)

xlabel('t')

ylabel('Vc')

show() Full Python Differential Equation Solver Code

# -*- coding: utf-8 -*-
from scipy import integrate
from pylab import *

def capVolts(Vc,t): # f(x) function
V = 12
R = 0.5
C = 1
return (V-Vc)/(R*C)

time = linspace(0.0,5.0,1000)
y = integrate.odeint(capVolts,0,time)
plot(time,y)
xlabel('t')
ylabel('Vc')
show()

That’s it

That’s it, just a few lines of code and you have a differential equation solver. You also get to practice and apply your coding skills. The steps outlined also make it easy to apply this method to any first order differential equation.

If you found this helpful or informative please share it with those you think it might help. Happy coding 🙂