Write Euler's method in Mathematica
I would like to write a function that has a loop in it which preforms the operations necessary for Euler's method. Below it my poor attempt.
In[15]:= Euler[icx_,icy_,h_,b_,diffeq_] :=
curx;
cury;
n=0;
curx = icx;
cury = icy;
While
[c开发者_开发百科urx != 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
To solve an ODE by Euler's 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 state that on your tags.
HTH!
Here is an example of solution without any 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}]
精彩评论