3

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

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
L1meta
  • 215
  • 1
  • 4

2 Answers2

9

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}]
J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
Sascha
  • 8,459
  • 2
  • 32
  • 66
2

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

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574