# Runge-Kutta method freezes or takes too much time

I want to solve differential equations iteratively to know better how algorithms work. From this discussion Problems with Runge-Kutta methods for different functions I know that the working Runge-Kutta method is:

ClearAll[RK4step]
RK4step[f_, h_][{t_, y_}] := Module[{k1, k2, k3, k4}, k1 = f[t, y];
k2 = f[t + h/2, y + h k1/2];
k3 = f[t + h/2, y + h k2/2];
k4 = f[t + h, y + h k3];
{t + h, y + h/6*(k1 + 2 k2 + 2 k3 + k4)}]
f[t_, {x_, v_}] := {v, 11 x + 10 v}

res = NestList[RK4step[f, 1/20], {0, {1, -1}}, 100];

Show[Plot[Exp[-x], {x, 0, 5}],
ListPlot[Transpose[{res[[All, 1]], res[[All, 2, 1]]}],
PlotStyle -> Orange]]


Which is proposed by @Szabolcs from Runge-Kutta implemented on Mathematica. So if I put new coefficients in f[t_, {x_, v_}] := {v, 11 x + 10 v}, everything works excellent. But in real life I have different functions... So for example, I have equation y''[x]-x*Sqrt[y]=0, for it f[t_, {x_, v_}] := {v,t*Sqrt[v]} and nothing is working :(

I need to click the "quit Kernel" button to stop wolfram. I have no idea why? And unfortunately without this knowledge code is nos so useful...

• Shouldn't the last component be t Sqrt[x]? – J. M.'s ennui May 16 '20 at 8:55
• 1. Your code involves typo like Srt, please double check it. 2. You're mixing up x and t. 3. Anyway, using {1., -1} instead of {1, -1} should resolve your problem. – xzczd May 16 '20 at 9:00
• @J.M. yes, thank you, I wrote wrong – Yura Holubeu May 16 '20 at 9:11
• @xzczd o, yeah, everything stopped freezing! thank you! – Yura Holubeu May 16 '20 at 9:13
• DEBUG TIP: First try it for just a few iterations, not 100; I'd probably try 1, but let me suggest 3 for you, so you can see the pattern, since I think you do not appreciate how Mathematica does its computations. Then compare A) NestList[RK4step[ff, 1/20], {0, {1, -1}}, 3], B) NestList[RK4step[ff, 1/20], {0, {1., -1}}, 3], and C) NestList[RK4step[ff, 1/20], {0, {1., -1.}}, 3]. There is a big difference between using exact input {1, -1} and approximate floating-point input {1., -1.}. – Michael E2 May 16 '20 at 18:16