In: Advanced Math
Plot the Euler’s Method approximate solution on [0,1] for the
differential equation
y* = 1 + y^2 and initial condition (a) y0 = 0 (b) y0 = 1, along
with the exact solution (see
Exercise 7). Use step sizes h = 0.1 and 0.05. The exact solution is
y = tan(t + c)
%%Matlab code for solving ode using Euler Improved Euler and
RK4
clear all
close all
%function for which Solution have to do
fun=@(t,y) 1+y.^2;
%initial guess
tinit=0; yinit=0;
%Answering Question for initial condition y(0)=0.
syms y(t)
eqn = diff(y,t) == 1+y.^2;
cond = y(0) == yinit;
ySol(t) = dsolve(eqn,cond);
%displaying result
fprintf('Exact solution y(t)=')
disp(ySol)
%Answering Question
%All step size
hh=[0.1 0.05];
fprintf('\nSolution Using Euler Method\n')
%loop for all step size and tend
for jj=1:length(hh)
h=hh(jj);
tend=1;
[t_euler,y_euler]=Euler(fun,tinit,yinit,tend,h);
y_ext=double(ySol(tend));
error =
abs(y_ext-y_euler(end));
fprintf('\tFor h=%2.4f
at t=%2.2f value of y=%f.\n ',h,t_euler(end),y_euler(end))
fprintf('\t Error E =
%f.\n\n',error)
figure(1)
hold on
plot(t_euler,y_euler)
end
plot(t_euler,ySol(t_euler))
legend('Euler h=0.1','Euler h=0.05','Actual Solution')
xlabel('t')
ylabel('y(t)')
title('Solution plot using Euler for y(0)=0')
box on
clear all
%function for which Solution have to do
fun=@(t,y) 1+y.^2;
%initial guess
tinit=0; yinit=1;
%Answering Question for initial condition y(0)=0.
syms y(t)
eqn = diff(y,t) == 1+y.^2;
cond = y(0) == yinit;
ySol(t) = dsolve(eqn,cond);
%displaying result
fprintf('Exact solution y(t)=')
disp(ySol)
%Answering Question
%All step size
hh=[0.1 0.05];
fprintf('\nSolution Using Euler Method\n')
%loop for all step size and tend
for jj=1:length(hh)
h=hh(jj);
tend=1;
[t_euler,y_euler]=Euler(fun,tinit,yinit,tend,h);
y_ext=double(ySol(tend));
error =
abs(y_ext-y_euler(end));
fprintf('\tFor h=%2.4f
at t=%2.2f value of y=%f.\n ',h,t_euler(end),y_euler(end))
fprintf('\t Error E =
%f.\n\n',error)
figure(2)
hold on
plot(t_euler,y_euler)
end
plot(t_euler,ySol(t_euler))
legend('Euler h=0.1','Euler h=0.05','Actual Solution')
xlabel('t')
ylabel('y(t)')
title('Solution plot using Euler for y(0)=1')
box on
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%Matlab function for Euler Method
function [t_euler,y_euler]=Euler(f,tinit,yinit,tend,h)
%Euler method
% h amount of intervals
t=tinit; % initial
t
y=yinit; % initial
y
t_eval=tend; % at what
point we have to evaluate
n=(t_eval-t)/h; % Number of steps
t_euler(1)=t;
y_euler(1)=y;
for i=1:n
%Eular Steps
m=double(f(t,y));
t=t+h;
y=y+h*m;
t_euler(i+1)=t;
y_euler(i+1)=y;
end
end
%%%%%%%%%%%%%%%%%%%%%% End of Code %%%%%%%%%%%%%%%%%%%%%%%