# How to implement adaptive step size Runge-Kutta Cash-Karp?

Trying to implement an adaptive step size Runge-Kutta Cash-Karp but failing with this error:

home/anaconda/lib/python3.6/site-packages/ipykernel_launcher.py:15: RuntimeWarning: divide by zero encountered in double_scalars from ipykernel import kernelapp as app


The ODE i am trying to solve (and using in the example below, transformed from higher order to system of 1st order ODEs) is the following:

$$u''(x)+u(x)+u(x)^3 =0 ~~{\rm with}~~ u(0)=u'(0)=1$$

Here is the implementation I am using:

def rkck(f, x, y, h, tol):
#xn = x + h
err = 2 * tol
while (err > tol):
xn = x + h
k1 = h*f(x,y)
k2 = h*f(x+(1/5)*h,y+((1/5)*k1))
k3 = h*f(x+(3/10)*h,y+((3/40)*k1)+((9/40)*k2))
k4 = h*f(x+(3/5)*h,y+((3/10)*k1)-((9/10)*k2)+((6/5)*k3))
k5 = h*f(x+(1/1)*h,y-((11/54)*k1)+((5/2)*k2)-((70/27)*k3)+((35/27)*k4))
k6 = h*f(x+(7/8)*h,y+((1631/55296)*k1)+((175/512)*k2)+((575/13824)*k3)+((44275/110592)*k4)+((253/4096)*k5))
yn4 = y + ((37/378)*k1)+((250/621)*k3)+((125/594)*k4)+((512/1771)*k6)
yn5 = y + ((2825/27648)*k1)+((18575/48384)*k3)+((13525/55296)*k4)+((277/14336)*k5)+((1/4)*k6)
err = yn4[-1]-yn5[-1]
h = 0.8 * h * (tol/err)**(1/float(5))
yn = yn4
return xn, yn

def integrate_sStepControl(f, t0, y0, tend, h, tol):
T = [t0]
Y = [y0]
t = t0
y = y0
while (t < tend):
h = min(h, tend-t)
t, y = rkck(f, t, y, h, tol)
T.append(t)
Y.append(y)
return np.array(T), np.array(Y)

def f_1(t,y):
return np.array([ y[1], -y[0]-(y[0])**3 ])

Y0_f1 = np.array([1.0,1.0])

# Execution
h = 0.05
tv, yv = integrate_sStepControl(f=f_1, t0=0.0, y0=Y0_f1, tend=100.0, h=h, tol=1.0E-05)
print("[ %20.15f, %20.15f]"%(yv[-1,0], yv[-1,1]) )
plt.plot(tv, yv)


Getting the error above, but it gets plotted. Don't know what I am doing wrong here :-/

• If I remember correctly, then you should be able to do timestepping with the first four evaluations already. You could check if those are correct by doing a fixed-stepsize forward simulation and see if it checks out. Then you can add the stepsize control later. – MPIchael Apr 25 at 11:09
• Somehow I think there's something wrong with my implementatio.. I can't get what is wrong, but it's not working the way it should.. – ZelelB Apr 25 at 14:19
• Perhaps you’re getting the ‘err’ variable value to be 0 sometimes, with respect to finite precision, so you’re getting a division by zero there. – spektr Apr 26 at 5:37
• But the rest of the implementation is right? @spektr – ZelelB Apr 26 at 7:47
• Answered at the cross-post stackoverflow.com/a/55863292/3088138 – LutzL Jun 13 at 7:56