# Plot results of Euler's Method

So this is my code for Euler's method to approximate ode's. f_ being the ode, t0_ the start of the interval, tf_ the end, y0_ initial condition, h_ the step size, and y_ is a given exact solution.

euler[f_, t0_, y0_, tf_, h_, y_] := Module[{},
t[0] = t0;
w[0] = y0;
n = Rationalize[(tf - t0)/h];
Do[
w[i] = w[i - 1] + h*f[t[i - 1], w[i - 1]];
t[i] = t[i - 1] + h,
{i, 1, n}];
Print["Euler's Method Results:"];
TableForm[
Table[{i, t[i], w[i], y[t[i]], Abs[w[i] - y[t[i]]]}, {i, 0, n}],
"Euler's \nMethod \nwi","Exact \nSolution\ny(ti)",
"Absolute \nError \n|wi-y(ti)|\n"}},
TableAlignments -> Center, TableSpacing -> {2, 5}
]
]


The code works fine so I'm not worried about that, but I can't figure out how to plot the Euler's method solution. I expect it to be something like

Plot[w[i], {i, 0, n}, PlotLabel -> "Exact solution",AxesLabel -> {"t", "y"}]


but I can't seem to make it work.

• Have you seen this? – J. M. is away Apr 9 '18 at 13:28
• Yeah I was just looking at that and I will admit I do not understand it. I'm not really a cs person, just a math student who got pulled into a mathematica class. My professor walked us through the code that I have, but we ran out of time before she showed us how to plot it. – JakeRyan34 Apr 9 '18 at 13:31
• Well, I'm not a "CS person" either. ;) Anyway: so you wrote this implementation of Euler's method yourself, or is this adapted from your prof's implementation? – J. M. is away Apr 9 '18 at 13:33
• Yeah it's adapted from hers. She pretty much gives everyone the code for an example and then changes the question a little bit on the homework. I guess so everyone does it in a similar way – JakeRyan34 Apr 9 '18 at 13:36
• I had asked because the programming style really isn't something I can endorse, but this isn't a good time to give your prof surprises. Anyway, try this: euler[f_, t0_, y0_, tf_, h_] := Module[{n, t, w}, t[0] = t0; w[0] = y0; n = Rationalize[(tf - t0)/h]; Do[w[i] = w[i - 1] + h f[t[i - 1], w[i - 1]]; t[i] = t[i - 1] + h, {i, 1, n}]; ListLinePlot[Table[t[i], w[i], {i, 0, n}]]]. – J. M. is away Apr 9 '18 at 13:40