I'm getting a wrong table result from my function.

I made a table of results that includes h and the error: Eh = max|y(t) y ̃(t)|, where y ̃ is my approximated solution. I'm using twostepmethod function with startingtimet =0, endingtimet =20, and stepsizes: h= 1/2^n for n=1, . . . , 10.
And I'm getting a totally wrong table which is
Table with h & Eh
h Eh
1.0e+225 *
0.0000 0.0000
0.0000 0.0000
0.0000 0.0000
0.0000 4.2965
0.0000 Inf
0.0000 Inf
0.0000 Inf
0.0000 Inf
0.0000 Inf
0.0000 Inf
Can you please fix my code to get a proper table?
this is my code
f=@(t,y) -y-3*t;
F=@(t) 3-3*t-2*exp(-t);
t0=0; y0=1;
te=20;
nn=1:10;
h = 1./2.^nn;
for ii=1:length(nn)
[ys, ts] = MyTwoStepMethod(f, t0, te, y0, h(ii));
Eh(ii) = max(abs(F(ts)-ys));
end
disp('Table with h & Eh'), disp(' h Eh')
disp([h',Eh'])
and this is my function
function [ys, ts] = MyTwoStepMethod(f, t0, te, y0, h)
ts = t0:h:te;
ys(1,1) = y0;
ys(1) = y0;
ys(2) = y0 + h*f(ts(1),ys(1));
for i = 2:length(ts)-1
ys(i+1) = -4*ys(i) + 5*ys(i-1) + h*(4*f(ts(i),ys(i))+2*f(ts(i-1),ys(i-1)));
end
end

7 件のコメント

Torsten
Torsten 2022 年 5 月 1 日
Does your strange "TwoStepMethod" have a name ?
Seungryul Lee
Seungryul Lee 2022 年 5 月 1 日
Will you plz give me any thoughts for that function:(
Torsten
Torsten 2022 年 5 月 1 日
Where did you get your TwoStepMethod from ? It looks wrong to me.
Seungryul Lee
Seungryul Lee 2022 年 5 月 1 日
編集済み: Torsten 2022 年 5 月 2 日
Write a function: function [y, ts] = MyTwoStepMethod(f, t0, te, y0, h) that implements a two-step method with the following form: yi+1 =4yi +5yi1 +h(4f(ti,yi)+2f(ti1,yi1)) using forward Euler for the first step. This function should accept as arguments the function f(t,y), the starting time t0, the ending time te, the initial condition y0, and the step size h. It should return the approximate solution y at all time points as well as the time points ts.
this was the exact problem I had, so I've made some changes from my original Euler method function, and know I have no idea how to code it . .
Torsten
Torsten 2022 年 5 月 2 日
編集済み: Torsten 2022 年 5 月 2 日
If this is the task, your code is correct.
But your method is unstable because the characteristic polynomial has the form x^2+4x-5 with roots -5 and 1.
Seungryul Lee
Seungryul Lee 2022 年 5 月 2 日
That's good. What about my code for displaying the table? Is that also correct?
Because I'm keep getting a silly table which I posted. It's giving me back 0s for h, which should not be 0s.
Torsten
Torsten 2022 年 5 月 2 日
Didn't you see that the values are to be multiplied by 1e225 ?
Give the 0's more digits by using
format long

サインインしてコメントする。

回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeTables についてさらに検索

製品

リリース

R2022a

質問済み:

2022 年 5 月 1 日

コメント済み:

2022 年 5 月 2 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by