Frage

Ich möchte eine Funktion schreiben, die eine Schleife in sich hat, die die Operationen für die Eulersche Verfahren notwendig Preforms. Darunter mein armer Versuch.

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
War es hilfreich?

Lösung

Um eine ODE von Euler-Methode in Mathematica zu lösen ist der Code:

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]

Andernfalls, wenn Sie bei den Hausaufgaben zu tun haben, geben Sie bitte an, dass auf Ihre Tags.

HTH!

Andere Tipps

Hier ist ein Beispiel für Lösung ohne explizite Schleife.

Wenn eine Schleife benötigt wird, lasse ich Sie es selbst tun.

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}]
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top