In: Advanced Math
Using MATLAB:
Consider the following Boundary Value Differential Equation:
y''+4y=0
y(0)=-2
y(π/4)=10
Which has the exact solution: y(x)= -2cos(2x)+10sin(2x)
Create a program that will allow the user to input the step size (in x), and two guesses for y'(0). The program will then use the Euler method along with the shooting method to solve this problem. The program should give the true error at y(π/8). Run your code with step sizes of π/400 and π/4000 and compare the errors. Chose any guesses for y'(0) that are reasonable. Also list the two errors you calculated.
For step size =0.007854 error in Euler method at x=pi/8
is 2.899593e-02.
For step size =0.000785 error in Euler method at x=pi/8 is
3.001448e-03.
%%Matlab code using Euler method for 2nd order differential
equation
clear all
close all
%Program for Euler method for question.
f=@(x,y1,y2)
y2;
%function (i)
g=@(x,y1,y2)
-4*y1;
%function (ii)
%two initial guesses
in_1=0; in_2=100; step_size=[pi/400 pi/4000];
for ij=1:2
%all guesses for Z_0 using shooting method
a_ini=linspace(in_1,in_2,10);
for ii=1:length(a_ini)
x_result(1)=0;y1_result(1)=-2;y2_result(1)=a_ini(ii); %initial
conditions
h=step_size(ij);
%step length
x_in=x_result(1);
%Initial x
x_max=pi/4;
%Final x
n=(x_max-x_in)/h;
%number of steps
%Euler 2d
iterations
for i=1:n
x_result(i+1)= x_result(i)+h;
y1_result(i+1)=
y1_result(i)+h*double(f(x_result(i),y1_result(i),y2_result(i)));
y2_result(i+1)=
y2_result(i)+h*double(g(x_result(i),y1_result(i),y2_result(i)));
end
yy1(ii)=y1_result(end);
end
p = interp1(yy1,a_ini,10);
%fprintf('\tThe value of y_dash(0)=z_0 using
Shooting method is %f\n',p)
clear x_result; clear y1_result; clear
y2_result
%solution using value of z_0
x_result(1)=0;y1_result(1)=-2;y2_result(1)=p; %initial
conditions
x_max=pi/8;
n=(x_max-x_in)/h;
%number of steps
for i=1:n
x_result(i+1)= x_result(i)+h;
y1_result(i+1)=
y1_result(i)+h*double(f(x_result(i),y1_result(i),y2_result(i)));
y2_result(i+1)=
y2_result(i)+h*double(g(x_result(i),y1_result(i),y2_result(i)));
end
%function for the exact
solution
f_ext=@(x)
-2*cos(2*x)+10*sin(2*x);
err=abs(f_ext(x_result(end))-y1_result(end));
fprintf('For step size =%f error in
Euler method at x=pi/8 is %e.\n',h,err)
end
%%%%%%%%%%%%%%%% End of Code
%%%%%%%%%%%%%%%%%