slightly off euler method code

1 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Time Series Objects 的更多信息

标签

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by