I am new to Mathematica and I would like to learn a bit more about functional programming.
At the moment I have assignments like programming different numerical methods (for integration: trapezoidal rule, simpson's rule ,.. , for differential equations: euler's method, midpoint Runge-Kutta, ..). I've been implementing all of the methods with procedural programing, with While
loops and For
loops, but now with Eluer's method I've started using functional programming and have used Table
and FoldList
instead of a For
loop. It comes together quite nicely. Here is an example:
euler[f_Symbol, y0_, {tz_, tk_}, h0_: 0.1] :=
Module[{t0 = tz, h = h0, n = Abs[tz - tk]/h0, Y, T, y},
y = FoldList[#1 + h*f[#1, #2] &, y0, Table[t0 + i*h, {i, 0, n - 1}]];
T = Table[t0 + i*h, {i, 0, n + 1}];
Y = Table[N[{T[[j]], y[[j]]}], {j, 1, n + 1}];
ListPlot[Y, Joined -> True, PlotRange -> All]
]
I would like to do something similar with the midpoint Runge-Kutta method, but I don't know how. Here is the procedural code:
midpointRK[f_, y0_, ta_, tb_, h0_: 0.1] :=
Module[{tA = ta, tB = tb, h = h0, n, Y, g, y},
n = Abs[tB - tA]/h;
y[0] = y0;
For[i = 0, i <= n, i++,
y[i + 0.5] = y[i] + (h/2)*f[y[i], tA + i*h];
g = f[y[i + 0.5], tA + i*h*0.5];
y[i + 1] = y[i] + h*g;
Y = Table[{N[tA + j*h], y[j]}, {j, 0, n}]
];
ListPlot[Y, Joined -> True, PlotRange -> All]
]
Can someone please help me in this regard and explain to me a little, what each command does?