Euler’s method in Mathematica
Math 330 
David McClendon

Command 1 (Defining code for Euler's method) :

From lecture we described a numerical method of approximating solutions to first-order differential equations of the form y' =ϕ(t,y) called Euler's method.  To implement Euler's method, first execute the following command once (this command will need to be executed once every time you restart Mathematica before you can apply it):

euler[f_,{t_,t0_,tn_},{y_,y0_},steps_]:=Block[{told=t0,yold=y0,thelist={{t0,y0}},t,y,h},h=N[(tn-t0)/steps];
Do[tnew=told+h;
ynew=yold+h*(f/.{t->told,y->yold});
thelist=Append[thelist,{tnew,ynew}];
told=tnew;
yold=ynew,{steps}];
Return[thelist];]

This command, in some sense, created a "black box" called euler which can henceforth be used to produce output obtained by Euler' s method.  After the above command is run once, you can then type in and execute commands like this (don' t execute this yet) :

Command 2 (Executing Euler's method) :

euler[3y, {t, 1, 3}, {y, -1}, 400]

This command performs Euler’s method for the ODE y’ = 3y where the initial point is ((Subscript[t, 0]), (Subscript[y, 0])) = (1,-1); the procedure stops when x = 3; there are 400 steps used.  This command will produce a (very long) list of points starting with (1,-1), (1.005, -1.015), and ending with ((Subscript[t, 400]), (Subscript[y, 400])) = (3, -385.849).  This is the same as the list of points ((Subscript[t, n]), (Subscript[y, n])) that you would produce if you did Euler’s method by hand.  If you only want to see the last number in the list, tweak the command by typing

euler[3y, {t, 1, 3}, {y, -1}, 400][[401]]

The number in the double brackets should be one more than the number of steps.

Command 3 (Sketching the points obtained from Euler's method) :

If you only care about a picture of the points you’d get from Euler’s method, you can use the following command.  It simply plots all the points ((Subscript[t, n]), (Subscript[y, n])) that you would obtain by executing Euler’s method.  Since there are so many points, it appears as though they make a curve (since the points are really close together):

ListPlot[euler[3y, {t, 1, 3}, {y, -1}, 400]]

Again, in this command the starting point is (1,-1), you stop at t = 3, and there are 400 steps used in the computation so there are 401 points plotted.