Solve the following ODE (ordinary differential equation) using your script and p
ID: 665999 • Letter: S
Question
Solve the following ODE (ordinary differential equation) using your script and plot the solution along with the exact solution on the same plot.
The ODE is y’= t2 + y, for 0 t 2
Exact solution is given by: yexact = 3et t2 2t 2
With initial condition (at t=0), y(0) = 1, for h = 0.25, use y(tn+1)=y(tn)+h*y’(tn) to calculate y(0.25), y(0.5), y(0.75) and so on until y(2) in the range 0 t 2. Where tn+1=tn+h, where h is step size.
Compute solutions to the ODE in the above example for h = 0.5, 0.25, 0.1, and 0.01 with
all other parameters remaining the same. Plot these four solutions along with the exact solution on the same graph. Adjust line styles using the figure menus. Show legend.
Explanation / Answer
Answer:
%File: fun.m
Function [T,Y]=fun(yfun,intr,h,y0)
T(1)=intr(1);
Y(1)=y0;
K=1;
While T(k)<intr(2)
T(k+1)=T(k)+h;
End
Y(k+1)=Y(k)+h*yfun(T(k),Y(k));
K=k+1;
End
%File: yfun.m
function yfun=yfun(t,y)
yfun=t^2+y;
end
%File:yexact.m
function yexact=yexact(t)
yexact=3*exp(t)-t.^2-2*t-2;
end
[T,Y]=fun(@yfun,[0 2],0.25,1);
Plot(T,y)
Hold on
T=0:0.01:2;
Title(‘Solutions of dy/dt=t^2+y’)
xlable(‘x’)
ylable(‘y’)
legend(‘Numerical solution’,’Analytical Solution’,’Location’,NorthWest’)
hold off
clear;
h=[0.01 0.10 0.25 0.50];
for i=1:4;
[T,Y}=fun(@yfun,[0,2],h(i),1);
plot(T,Y)
hold on;
end
t=0:0.01:2;
plot(t,yexact(t),’t’)
axis right
xlable(‘x’)
ylable(‘y’)
hold off
length(‘h=0.01’,’h=0.10’,’h=0.25’,’h=0.50’,’Solution’, ,’Location’,NorthWest’)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.