slightly off euler method code

2 views (last 30 days)
Cassandra Meyer
Cassandra Meyer on 21 Jun 2022
Edited: Torsten on 21 Jun 2022
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)

Accepted Answer

Torsten
Torsten on 21 Jun 2022
Edited: Torsten on 21 Jun 2022
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

More Answers (0)

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!