Решете моделната задача
u’(x)=-10u, 0<x<=1,
u(0)=1
при n=4, 20, 100 и сравнете с точното решение.

Явен метод на Ойлер

explicitEulerMP[n_]:= (
h=1/n;
y=Table[0,{n+1}];

y[[1]] = 1;
For[i=1, i<n+1, i++,
y[[i+1]] = y[[i]]-10.*h*y[[i]]
];

y
)

exact[x_]:=E^(-10x);
plotExact = Plot[exact[x],{x,0, 1}, PlotStyle->Red, PlotRange->All];

n=100(*4,20*);
times=Table[i*1/n,{i,0,n}];
appr = explicitEulerMP[n];
plotAppr = ListPlot[Transpose[{times,appr }], PlotMarkers->●];
Show[plotExact, plotAppr]
ListPlot[Transpose[{times,exact[times]-appr}], PlotMarkers->●]

Animate[
exact[x_]:=E^(-10x);
plotExact = Plot[exact[x],{x,0, 1}, PlotStyle->Red, PlotRange->All];
times=Table[i*1/n,{i,0,n}];
appr = explicitEulerMP[n];
plotAppr = ListPlot[Transpose[{times,appr}], PlotMarkers->●];
plotError = ListPlot[Transpose[{times,exact[times]-appr}],PlotRange->{{0,1},{0,1}}, PlotMarkers->●];

GraphicsRow[{Show[plotExact, plotAppr], plotError}],
{n, 4, 100,4}]

Неявен метод на Ойлер

implicitEulerMP[n_]:= (
h=1/n;
y=Table[0,{n+1}];

y[[1]] = 1;
For[i=1, i<n+1, i++,
initialGuess = y[[i]]+h*(-10)y[[i]];
y[[i+1]]=yNew/.FindRoot[yNew==  y[[i]]+h*(-10)yNew,{yNew,initialGuess}]
];

y
)

Manipulate[
exact[x_]:=E^(-10x);
plotExact = Plot[exact[x],{x,0, 1}, PlotStyle->Red, PlotRange->All];
times=Table[i*1/n,{i,0,n}];
appr = implicitEulerMP[n];
plotAppr = ListPlot[Transpose[{times,appr}], PlotMarkers->●];
plotError = ListPlot[Transpose[{times,Abs[exact[times]-appr]}],PlotRange->{{0,1},{0,1}}, PlotMarkers->●];

GraphicsRow[{Show[plotExact, plotAppr], plotError}],
{n, 4, 100,4}]

За магистрите: Неявен метод на Ойлер – решаване на нелинейните уравнения с метод на Нютон

Newton[g_,x0_, tol_, maxIter_]:=(
xCurrent = x0;
xNext = xCurrent - g[xCurrent]/g'[xCurrent];
iter=1;

While[Abs[xCurrent-xNext]≥tol && iter<maxIter,
xCurrent = xNext;
xNext = xCurrent - g[xCurrent]/g'[xCurrent];
iter++;
];

xNext
)

LS[x_]:=x^2-2x+1.+Sin[x]+Log[x]
Newton[LS,10,0.0000001,100]

FindRoot[LS[x]==0,{x,10}]

implicitEulerWithNewtonMP[n_]:= (
h=1/n;
y=Table[0,{n+1}];

y[[1]] = 1;
For[i=1, i<n+1, i++,
initialGuess = y[[i]]+h*(-10)y[[i]];
LS[yNew_]:=yNew-(  y[[i]]+h*(-10)yNew);
y[[i+1]]=Newton[LS,initialGuess,0.0000001,100]
];

y
)

Manipulate[
exact[x_]:=E^(-10x);
plotExact = Plot[exact[x],{x,0, 1}, PlotStyle->Red, PlotRange->All];

times=Table[i*1/n,{i,0,n}];
appr = implicitEulerWithNewtonMP[n];
plotAppr = ListPlot[Transpose[{times,appr}], PlotMarkers->●];
plotError = ListPlot[Transpose[{times,Abs[exact[times]-appr]}],PlotRange->{{0,1},{0,1}}, PlotMarkers->●];

GraphicsRow[{Show[plotExact, plotAppr], plotError}],
{n, 4, 100,4}]