필터 지우기
필터 지우기

slightly off euler method code

조회 수: 1 (최근 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 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