Program for Euler's Method
The Maple code below can be used to solve many initial value problems of the form
,
You can cut and paste this code to other worksheets. Note that you must also cut and paste to the other worksheet the definition of the utility function iterate that is defined in the first section in this worksheet entitled Activate me before using this worksheet. For convenience we have placed both the utility function and the Euler's Method program below. Thus it is easy to copy and paste both of them to your other worksheet.
To use the program you should modify its first four lines. In the first line define your function
. You may change the variables
and
to any others convenient for your problem. In particular the independent variable may be changed to
for the many initial-value problems in which it represents time. Change the second line to fit the initial condition for the problem. The value of
endOfInterval
determines the end point of the interval on which you want to plot the solution function (the initial point P0 determines the beginning of this interval). Note that the value of
endOfInterval
may be smaller than
if you wish to plot the solution curve to the
left
of the initial point. The value of
numPts
may be changed to a larger value to achieve greater accuracy. (100 is a good value; larger values increase the accuracy of the approximation but can add significant computing time. Values more than several thousand can use significant memory, since a list of points of this length is being created.)
Cut and paste the following two input cells to the worksheet in which you wish to use Euler's Method.
>
# This execution cell defines a useful funtion that enables
# us to iterate a function a given number of times with a
# given starting value. It generates a list
# [a, f(a), f(f(a)), f(f(f(a))), ...] (with n+1 terms)
iterate:=proc(f,a,n)
local term,result,i;
term:=a;
result:=a;
for i from 1 to n do
term:=f(term);
result:=result,term;
od;
RETURN([result]);
end:
>
# EULER'S METHOD:
# This execution cell generates a numerical solution for an initial
# value problem. The first four lines should be specialized to match
# your initial value problem. The remaining lines should not be
# changed. (The function "iterate" used in this program must be
# defined before running the program.)
f:=(x,y)->-x/y;
P0:=[0,1];
endOfInterval:=1;
numPts:=100;
Euler:=P->[P[1]+deltaI,P[2]+deltaI*f(P[1],P[2])]:
deltaI:=evalf((endOfInterval-P0[1])/numPts):
with(math3):
clear(i):
soln:=iterate(Euler,P0,numPts):
plot(soln);
Go back