# Plotting several numerical solutions plus the analytic solution of ODE in one plot

I want to be able to plot several numerical solutions of an ODE plus its analytical solution in one plot in order to see how the numerical solutions converge towards the analytical one w.r.t. the number of steps. The methods I'm using is Euler's method for the equation $y'(t) = 1-t +4y(t), y(0)=1$

The code I have so far is:

y[0]=1;
Do[y[n+1]=y[n]+0.01(1-0.01n+4y[n]), {n,0,99}]
y[100]


Is this doable? Thanks in advance for any help :)

-
Both Plot and ListPlot will accept lists of functions/lists to plot. –  image_doctor Nov 12 '12 at 16:23
And you can use Show to combine plots –  ssch Nov 12 '12 at 16:38
For Euler's method: see this related question. –  Ｊ. Ｍ. Nov 12 '12 at 16:49
Thanks guys, this was helpfull! –  L1meta Nov 12 '12 at 17:16

Sascha showed you how to use the built-in "ExplicitEuler" option. You mention

I want to be able to plot several numerical solutions of an ODE, plus its analytical solution in one plot, in order to see how the numerical solutions converge...

Here's one way to generate "Lady Windermere's fan":

yTrue = y /. First @ DSolve[{y'[t] == 1 - t + 4 y[t], y[0] == 1}, y, t];

pts = Table[
With[{ya = y /. First @
NDSolve[{y'[t] == 1 - t + 4 y[t], y[0] == 1}, y, {t, 0, 1},
Method -> "ExplicitEuler", StartingStepSize -> 2^-k]},
Transpose[Append[ya["Coordinates"], ya["ValuesOnGrid"]]]], {k, 1, 5}];

Show[Plot[yTrue[t], {t, 0, 1}, PlotStyle -> Directive[Thick, Dashed, Gray]],
ListPlot[pts, Joined -> True, Mesh -> All, PlotMarkers -> Automatic],
Axes -> None, Frame -> True]


Here, the gray dashed curve is the solution obtained from DSolve[].

-

Instead of implementing an explicit Euler method on your own, you could as well use the built-in option of NDSolve: (the value following StartingStepSize is your actual step size for the whole method since "ExplicitEuler" has no adaptive step size):

AnalyticalSolution = DSolve[{y'[t] == 1 - t + 4*y[t], y[0] == 1}, y, t]
NumericalSolution = NDSolve[{y'[t] == 1 - t + 4*y[t], y[0] == 1}, y, {t, 0, 10},
Method -> "ExplicitEuler", StartingStepSize -> 0.01]
Plot[{y[t] /. NumericalSolution, y[t] /. AnalyticalSolution}, {t, 0, 10}]

-
Awesome, thanks! –  L1meta Nov 12 '12 at 16:55