In: Advanced Math
differential equation for the initial condition y(0) = 0.5 and plot the result on the direction
field graph you produced in paragraph 1. Then do the same for the results of using the Euler Method with step sizes of 0.01 and then 0.005.
find the approximate the value of y when x = 4 using the Euler Method for each of the three different step sizes you used in paragraph 2.
Type or write:
“For the Euler Method with a step size of 0.1, y(4) =”,
followed by the answer accurate
to five decimal places.
“For the Euler Method with a step size of 0.01, y(4) =”,
followed by the answer accurate
to five decimal places.
“For the Euler Method with a step size of 0.005, y(4) =”,
followed by the answer accurate
to five decimal places.
Type or write:
“For the fourth-order Runge-Kutta Method with a step size of 0.1,
y(4) =”, followed by
the answer accurate to five
decimal places.
“For the fourth-order Runge-Kutta Method with a step size of 0.01,
y(4) =”, followed by
the answer accurate to five
decimal places.
“For the fourth-order Runge-Kutta Method with a step size of 0.005,
y(4) =”, followed by
the answer accurate to five decimal places.
%Matlab code for numerical solution of ode using RK4
method
clear all
close all
%function for which Solution have to do
fun=@(x,y) exp(y).*sin(5*x);
%initial condition
xinit=0; yinit=0.5;
xend=4;
%all step sizes
hh=[0.1 0.01 0.005];
for i=1:3
h=hh(i);
[x_elr,y_elr]=euler_method(fun,yinit,xinit,xend,h);
fprintf('\tUsing Euler, for h=%1.3f value of
x(%2.2f) is %f\n',h,x_elr(end),y_elr(end))
[x_rk4,y_rk4]=RK4(fun,yinit,xinit,xend,h);
fprintf('\tUsing RK4, for h=%1.3f value of
x(%2.2f) is %f\n',h,x_rk4(end),y_rk4(end))
end
plot(x_rk4,y_rk4,'linewidth',2)
hold on
plot(x_elr,y_elr,'--')
ylabel('x')
xlabel('y(x)')
title('x vs. y(x) plot')
legend('RK4 Solution','Euler Solution','location','best')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%Matlab code for Euler's forward
function [t_result,y1_result] = euler_method(f,y0,t0,tend,h)
%function for Euler equation solution
%all step size
N=(tend-t0)/h;
%Initial values
%t end values
tn=t0:h:tend;
% Euler steps
y1_result(1)=y0;
t_result(1)=t0;
fprintf('\n\tFor step size %2.2f\n',h)
for i=1:length(tn)-1
t_result(i+1)=
t_result(i)+h;
y1_result(i+1)=y1_result(i)+h*double(f(t_result(i),y1_result(i)));
%fprintf('At x=%2.2f
y(%2.2f)=%f\n',t_result(i+1),t_result(i+1),y1_result(i+1))
end
end
%%Matlab function for Runge Kutta Method
function [t_rk,y_rk]=RK4(f,yinit,tinit,tend,h)
% RK4 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_rk(1)=t;
y_rk(1)=y;
for i=1:n
%RK4 Steps
k1=h*double(f(t,y));
k2=h*double(f((t+h/2),(y+k1/2)));
k3=h*double(f((t+h/2),(y+k2/2)));
k4=h*double(f((t+h),(y+k3)));
dy=(1/6)*(k1+2*k2+2*k3+k4);
t=t+h;
y=y+dy;
t_rk(i+1)=t;
y_rk(i+1)=y;
end
end
%%%%%%%%%%%%%%%%%%%%%% End of Code %%%%%%%%%%%%%%%%%%%%%%%