slightly off euler method code

2 ビュー (過去 30 日間)
Cassandra Meyer
Cassandra Meyer 2022 年 6 月 21 日
編集済み: Torsten 2022 年 6 月 21 日
This code works when I call it, but the answer is so off that I think I did something wrong.
function [t,y] = eulerMethod(f, dt, Tf, t0, y0)
t(1) = t0;
y(1) = y0;
numSteps = (Tf - t0)/dt;
for ind=1:numSteps
m = f(t(ind),y(ind));
t(ind+1) = t(ind)+dt*f(Tf);
y(ind+1) = y(ind)+dt*m;
ind = ind+1;
end
end
I called it for the following function, but Euler gave an answer in the four thousands when f(2) is close to 6. Any help or guidance would be appreciated.
f = @(t,y) exp(t) - t;
fSol = @(t) exp(t) - t.^2/2;
[t,y]= eulerMethod(f,0.2,2,0,1)
euler = vpa(y(end))
f(2)

採用された回答

Torsten
Torsten 2022 年 6 月 21 日
編集済み: Torsten 2022 年 6 月 21 日
f = @(t,y) exp(t) - t;
fSol = @(t) exp(t) - t.^2/2;
[t,y]= eulerMethod(f,0.2,2,0,1);
plot(t,y)
hold on
plot(t,fSol(t))
function [t,y] = eulerMethod(f, dt, Tf, t0, y0)
t(1) = t0;
y(1) = y0;
numSteps = (Tf - t0)/dt;
for ind=1:numSteps
m = f(t(ind),y(ind));
t(ind+1) = t(ind)+dt;
y(ind+1) = y(ind)+dt*m;
end
end

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeTime Series Objects についてさらに検索

タグ

製品


リリース

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by