Euler's Method and exact solution plot
Show older comments
when i run the code below, the plots do not look correct to me. As when i make the time step smaller the eulers should get more accurate, thus closer matching the exact solution? But when i do this they eulers and exact solution seem to get further apart on the plot.
clear;
h=0.05; % time step
t=0:h:4; %time range
y=zeros(size(t)); % set y array all 0's to same size as t
y(1)=2; % set initial condition at time 0 to 2
n=numel(y);
dydt = 4*exp(0.8*t) - 0.5*y;
exact_sol=(4/1.3)*(exp(0.8*t)-exp(-0.5*t))+2*exp(-0.5*t); %This is the exact solution to dy/dt
for i=1 : n-1 %for loop to interate through y values for
y(i+1)= y(i)+ h * dydt(i); % the Euler method
end
plot(t,y) %plot Euler
hold on
plot(t,exact_sol,'red'); % plots the exact solution to this differential equation
legend('Euler','Exact'); % adds a legend
grid on
Accepted Answer
More Answers (0)
Categories
Find more on Equation Solving in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
