Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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 :)

share|improve this question
2  
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. –  J. M. Nov 12 '12 at 16:49
    
Thanks guys, this was helpfull! –  L1meta Nov 12 '12 at 17:16

2 Answers 2

up vote 0 down vote accepted

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[].

share|improve this answer

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}]
share|improve this answer
    
Awesome, thanks! –  L1meta Nov 12 '12 at 16:55

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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