Mathematica – Euler’s method for systems

Here is a description of how to implement Euler’s method for a system.

We focus on a simple example:
\frac{dx}{dt} = f(x,y)
\frac{dy}{dt} = g(x,y)
f(x,y) = x+y and g(x,y) = -x

First, let’s put in the functions which define the system

f[x_, y_] := x + y;
g[x_, y_] := -x;

Next, we make a StreamPlot of the vectorfield

sp = StreamPlot[{f[x, y], g[x, y]}, {x, -5, 5}, {y, -5, 5}];

Now we implement Euler’s method with \Delta t = 0.05 and 100 time steps by setting setting up three recursion relations:
t_0 =0 \qquad t_{k+1} = t_k + \Delta t
x_0 =0 \qquad x_{k+1} = x_k + \Delta t \cdot f(x_k, y_k)
y_0 =0.5 \qquad x_{k+1} = y_k + \Delta t \cdot g(x_k, y_k)
The code which does this is the following:

deltat = .05;
steps = 100;
evalues = RecurrenceTable[{
    t[0] == 0,
    x[0] == 0,
    y[0] == .5,
    t[k + 1] == t[k] + deltat,
    x[k + 1] == x[k] + deltat*f[x[k], y[k]],
    y[k + 1] == y[k] + deltat*g[x[k], y[k]]
   {t, x, y},
   {k, 0, steps}];

Notice that I’ve put the semicolon after the Grid[evalues];. This suppresses the output. You can remove the semicolon to look at the list of numbers, which is helpful for finding errors.

Since we are only interested in plotting on the x - y axis, we make a second table consisting only of the x and y values:

pvalues = Table[{
    evalues[[k, 2]],
    evalues[[k, 3]]
    }, {k, 1, steps + 1}];

You can use the Grid[pvalues] command to make sure you have the same list of numbers.

Now we can plot the numerical result on top of the StreamPlot:

eplot = ListLinePlot[pvalues, PlotMarkers -> Automatic, 
   PlotStyle -> Red];
Show[sp, eplot]
This entry was posted in Differential equations, Mathematica. Bookmark the permalink.

Leave a comment here

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s