2
$\begingroup$

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 with respect to the number of steps. The method 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 :)

$\endgroup$
  • 2
    $\begingroup$ Both Plot and ListPlot will accept lists of functions/lists to plot. $\endgroup$ – image_doctor Nov 12 '12 at 16:23
  • $\begingroup$ And you can use Show to combine plots $\endgroup$ – ssch Nov 12 '12 at 16:38
  • $\begingroup$ For Euler's method: see this related question. $\endgroup$ – J. M. will be back soon Nov 12 '12 at 16:49
1
$\begingroup$

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]

Lady Windermere's fan

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

$\endgroup$
8
$\begingroup$

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}]
$\endgroup$
  • $\begingroup$ Awesome, thanks! $\endgroup$ – L1meta Nov 12 '12 at 16:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.