Filter löschen
Filter löschen

slightly off euler method code

1 Ansicht (letzte 30 Tage)
Cassandra Meyer
Cassandra Meyer am 21 Jun. 2022
Bearbeitet: Torsten am 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)

Akzeptierte Antwort

Torsten
Torsten am 21 Jun. 2022
Bearbeitet: Torsten am 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

Weitere Antworten (0)

Kategorien

Mehr zu Time Series Objects finden Sie in Help Center und File Exchange

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by