A.4 Python code to solve ODEs with IVPs

The following code is written in Python 3 and can be run in Windows, Linux, or Mac OS. The internet provides plenty of resources for finding out how to run Python on your own computer. In addition to python, you will need to install the python package called “matplotlib”, which can be found on the internet or is also a part of the “scipy” package.

The code implements the RK4 stepper in a simple way (that is, the step-size is held constant). In order to use the code, you must first write the ODEs in the form of \(n\) first order coupled ODEs:

\begin{align} \frac{dy_0}{dx}=f_0(y_0,y_1,\dots ,y_n,x)\\ \frac{dy_1}{dx}=f_1(y_0,y_1,\dots ,y_n,x)\\ \dots\\ \frac{dy_n}{dx}=f_n(y_0,y_1,\dots ,y_n,x) \end{align}

The functions are then the following:

In principle the code can be used without understanding too many of the details. The user needs to modify dy inside the derivs() function, set the initialConditions list, and decide on the stepping parameters when calling solve().

#! /usr/bin/python

#from ROOT import TGraph, TCanvas
import matplotlib.pyplot as plt

#RK4 stepper
def step(stepsize, yin, x, derivs):
    dy=derivs(x,yin)
    k1=[]
    y2=[]
    for i in range(0,len(yin)):
        k1.append(stepsize*dy[i])
        y2.append(yin[i]+0.5*k1[i])

    dy=derivs(x+0.5*stepsize,y2)
    k2=[]
    y3=[]
    for i in range(0,len(yin)):
        k2.append(stepsize*dy[i])
        y3.append(yin[i]+0.5*k2[i])

    dy=derivs(x+0.5*stepsize,y3)
    k3=[]
    y4=[]
    for i in range(0,len(yin)):
        k3.append(stepsize*dy[i])
        y4.append(yin[i]+k3[i])

    dy=derivs(x+stepsize,y4)
    k4=[]
    yout=[]
    for i in range(0,len(yin)):
        k4.append(stepsize*dy[i])
        yout.append(yin[i]+k1[i]/6.0+k2[i]/3.0+k3[i]/3.0+k4[i]/6.0)

    return yout

def solve(stepsize,x0,nSteps,derivs,initialConditions):
    y=[]
    y.append([x0,initialConditions])
    print("Initial ", y)
    for i in range (0,nSteps):
      x=x0+i*stepsize
      #the new value is the one at the END of the step, so label it x+stepsize
      y.append([x+stepsize,step(stepsize,y[len(y)-1][1:][0],x,derivs)])
    return y

def plot(yx):
    ny=len(yx[1])
    for i in range(0,ny):
        y=[]
        x=[]
        for j in range (0,len(yx)):
            x.append(yx[j][0])
            y.append(yx[j][1][i])
        plt.plot(x,y)
        plt.show()

#problem-specific derivatives
def derivs(x,yin):
    m=1
    k=0.5
    c=2
    print("derivatives at ", x, " ", yin)
    dy=[yin[1],-1.0/m*(k*yin[0]+c*yin[1])]
    return dy

########################################
########################################
#initial conditions for each function
initialConditions=[1,0]
yx=solve(0.1,0.0,100,derivs,initialConditions)

#Do the drawing
plot(yx)