Write Euler Method in Mathematica

I would like to write a function in which there is a loop that performs the operations necessary for the Euler method. Below is my poor attempt.

In[15]:= Euler[icx_,icy_,h_,b_,diffeq_] :=
curx;
cury;
n=0;
curx = icx;
cury = icy;

While
[curx != b, 

    Print["" + n + " | " + curx + cury];
    n++;

    dq = StringReplace[diffeq, "y[x]" -> curx];
    dq = StringReplace[dq, "x" -> cury];
    curx+=h;
    cury=cury+h*dq;


]


In[21]:= Euler[0, 0, .1, 1, e^-y[x]]

Out[21]= icx
+3
source share
2 answers

To solve ODE using the Euler method in Mathematica, the code is:

Clear["Global`*"]; 
s = NDSolve[{y'[x] == Exp[-y[x]], y[0] == 0}, y, {x, 0, 1}, 
    Method -> {"FixedStep", Method -> "ExplicitEuler"}, 
    MaxSteps -> 20000];
Plot[Evaluate[y[x] /. s], {x, 0, 1}, PlotRange -> Full]

Otherwise, if you are dealing with homework, please indicate what is in your tags.

NTN!

+1
source

Here is an example solution without an explicit loop.

If a loop is needed, I let you do it yourself.

EulerODE[f_ /; Head[f] == Function, {t0_, y0_}, t1_, n_] := 
 Module[{h = (t1 - t0)/n // N, tt, yy},
 tt[0] = t0; yy[0] = y0;
 tt[k_ /; 0 < k < n] := tt[k] = tt[k - 1] + h;
 yy[k_ /; 0 < k < n] := 
 yy[k] = yy[k - 1] + h f[tt[k - 1], yy[k - 1]];
 Table[{tt[k], yy[k]}, {k, 0, n - 1}]
 ];

ty = EulerODE[Function[{t, y}, y/t + y^2/t^2], {1, 1}, 2, 100] ;

Plot[Interpolation[ty][t], {t, 1, 2}]
0
source

Source: https://habr.com/ru/post/1771132/


All Articles