Forward, backward and modified Euler methods; plots do not come as usual, HELP
조회 수: 6 (최근 30일)
이전 댓글 표시
clear all;
close all;
clc
%y'=4y (y'=dYdt in the code)
%t=0 to t=3
%y(0)=1
%y=exp(4t)
t0=0; %initial time
tf=3; %final time
dt=0.01; %step size
t=t0:dt:tf; %indep variable - time
y(1)=1; %initial cond for forward euler
y2(1)=y(1); %initial cond for backward euler
ym(1)=y(1); %initial cond for mod euler
yex(1)=y(1); %exact y value at t=0
for i=1:length(t)-1
dYdt(i)=4*y(i);
y(i+1)=y(i)+dt*dYdt(i); %Forward euler eqn
dYdt(i+1)=4*y(i+1);
y2(i+1)=y(i)+dt*dYdt(i+1); %Backward euler eqn
ym(i+1)=y(i)+(dYdt(i)+dYdt(i+1))*0.5*dt; %Modified euler eqn
yex(i+1)=exp(4*t(i+1)); %Exact eqn
end
figure(1)
hold on
plot(t,y,'ro') % plot of forward E.
plot(t,y2,'bo') % plot of backward E.
plot(t,ym,'mo') % plot of mod E.
plot(t,yex,'Linewidth',1.2) %plot of exact fun.
xlabel('time (s)')
ylabel('y(t)')
title('For/Backward & Modified Euler vs. Exact solution')
legend('Forward Euler','Backward Euler','Modified Euler','Exact solution')
hold off
I want to know whether there is any error in this and not another method to the same thing. Thanks!
댓글 수: 2
답변 (1개)
KSSV
2020년 6월 14일
편집: KSSV
2020년 6월 14일
The solution of numerical model depends on the number of discretization. The more the discretization (time step dt here) the close your solution will be to analytical. Try changing the time step. Try
dt = 0.001 ;
You can do a parametric study, take different time steps and see.
Note: You need to initialize the solution i.e the variables which are inside loop and you are saving. They should be initilaized. Read about initializing.
참고 항목
카테고리
Help Center 및 File Exchange에서 Ordinary Differential Equations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!