# Use Euler method to solve differential equation

1. Use Euler's Method or the Modified Euler's to solve the differential equation ${dy/dt=y^2+t^2-1, y(-2)=-2}$ on $[- 2, 2]$. Take h = 0.2 (n = 20 iterations).

2. See if Mathematica will give an analytic solution to this problem.

If it does compare the analytic solution found in Problems 1 and 2.

If Mathematica will not give an analytic solution, compare your solutions to the numerical solution on $[-2, 2]$ given by Mathematica.

For the first problem, I am confused of the interval is not $[0,2]$ but $[-2,2]$ I have no idea with these two problems, can anyone help me?

• Hello ! Welcome ! I am sorry, but you clearly did not research the problems in question. Nevertheless I will not give you a tip on the first one, but on the second - look up DSolve in the documentation centre. – Sektor Feb 6 '14 at 4:50
• Thank you, I will look up NDSolve and DSolve – vicky1229 Feb 6 '14 at 5:00
• A related question. – J. M.'s technical difficulties May 27 '15 at 5:55

Edit

I edited to replace h with N@h as suggested by MichaelE2, to prevent Mathematica slowdown if exact h is provided by the user.

Note for future users: I initially had a procedural approach posted, if you're interested in that method see the edit history. I present a Functional approach, this is Mathematica after all.

SetAttributes[eulerMethod, HoldAll];

eulerMethod[func_, {x_, x0_, xmax_}, {y_, y0_}, h_] :=
Module[{EulerStep, hh = N@h},
EulerStep[{xi_, yi_}] := Module[{xold = xi, yold = yi, xnew, ynew},
xnew = xold + hh;
ynew = yold + hh ReleaseHold[Hold[func] /. {HoldPattern[x] -> xold,
HoldPattern[y] -> yold}]; {xnew, ynew}];
NestList[EulerStep, {x0, y0}, Round[(xmax - x0)/hh]
]
]


Usage

sol = eulerMethod[y^2 + t^2 - 1, {t, -2, 2}, {y, -2}, 0.2];


You can compare it to the built in NDSolve by plotting both in the range [-2, 2]

ListLinePlot[sol, Filling -> Axis]


For NDSolve:

nd = NDSolve[{y'[t] == y[t]^2 + t^2 - 1, y[-2] == -2}, y[t], {t, -2, 2}];


Then

Plot[y[t] /. nd, {t, -2, 2}, Filling -> Axis]


Clearly, our eulerMethod needs more iteration (smaller step size) to get close to the more accurate NDSolve

If we increase the number of iterations (decrease h) we nail the accuracy

sol2 = eulerMethod[y^2 + t^2 - 1, {t, -2, 2}, {y, -2}, 0.01]

ListLinePlot[sol2, PlotStyle -> {Red, Thick}, Filling -> Axis, FillingStyle -> Darker@Green]


Clearly, this looks very much like the result from NDSolve

You can get an exact solution using DSolve as follows:

DSolve[{y'[t] == y[t]^2 + t^2 - 1, y[-2] == -2}, y[t], t]

• @vicky1229, RunnyKine, You might want to consider apply N somewhere in case someone does eulerMethod[y^2 + t^2 - 1, {t, -2, 2}, {y, -2}, 1/100]. See also mathematica.stackexchange.com/questions/22042/…. (+1) – Michael E2 May 18 '15 at 19:45
• @MichaelE2, I just saw your comment I haven't been active in a while. I'll fix it. Thanks for pointing that out and for the upvote. – RunnyKine May 27 '15 at 5:31