b
Download ODE_Solver.py

NOTE:

In reality you should probably be using scipy.odeint() rather than this code, as it is written in C and much faster. However, this provides a clear example of how to implement an adaptive step-size embedded RK4/5 numeric integration algorithm.

This is a module I wrote for Python, can be used to numerically integrate ordinary differential equations. The method used is a Runge-Kutta 5th order numeric step, with an adaptive step-size determined via an embedded 4th order Runge-Kutta calculation. The methodology (and notation used in the file) is pulled from Formulation and notation taken from Numerical Recipes in Fortran 77, Second Edition (1992) by William H. Press, et.al. Note that the book can be found online here.

Documentation

def control(deriv, tol, y0, t0, h, tmax, v=False)
This funciton takes in a python function that returns the derivative, a tolerance for error between RK5 and RK4, initial conditions on y (dependant) and t (independant) as well as an initial step size.

Keyword arguments:
v - Verbose

Example (verbose)

In [1]: run ODE_solve.py [--.--] Starting. Importing libraries. [0.054] Defining parameters and functions. [0.000] Solving with initial condition (1.00, 0.00), step size of 0.10 from t=0...2.00 [0.000] Reduced step size from 1.0000e-01 to 1.0381e-02 at t = 0.00 [0.000] Increased step size from 1.0381e-02 to 1.1420e-02 at t = 0.18 [0.001] Increased step size from 1.1420e-02 to 1.2566e-02 at t = 0.42 [0.001] Increased step size from 1.2566e-02 to 1.3891e-02 at t = 0.67 [0.001] Increased step size from 1.3891e-02 to 1.5346e-02 at t = 0.92 [0.001] Increased step size from 1.5346e-02 to 1.6922e-02 at t = 1.16 [0.001] Increased step size from 1.6922e-02 to 1.8722e-02 at t = 1.42 [0.002] Increased step size from 1.8722e-02 to 2.0626e-02 at t = 1.66 [0.002] Increased step size from 2.0626e-02 to 2.2759e-02 at t = 1.91 [0.002] Done. 146 iterations, 137 points