Problem in executing the code
Show older comments
%%
clc;
clear;
%Q.) 7
%Evaluate integral of exp(-x)/sqrt(x) over [0,1].
%(a) Using a rectangular rule
%(b) Make a change of variables x = t^2 and use rectangular rule on new variable.
%After applying change of variables we get the integral to find out equal
%to integral of exp(-x^2) over [-1,1].
syms f(x);
f(x) = exp(-x^2);
syms g(t);
g(t) = exp(-t)/t^(1/2);
a = -1;
b = 1;
N = [5 10 20 50 100 200 500 1000];
exact_int = 1.4936482656248540507989; % exact value of integral evauated from wolfram alpha.
Ngrids = 8; % Number of different grids
h = zeros(Ngrids,1);
rect_1 = zeros(Ngrids,1);
rect_2 = zeros(Ngrids,1);
for i = 1 : Ngrids
h(i)=(b-a)/N(i); % Different-different grid spacing
x = linspace(a,b,N(i)+1); % Grid Points
t = linspace(a,b,N(i)+1); % Grid Points
y1 = 0.5*(x(1:N(i))+x(2:N(i)+1));% Midpoints of each panel
y2 = 0.5*(t(1:N(i))+t(2:N(i)+1));% Midpoints of each panel
rect_1(i)=h(i)*sum(f(y1)); % Rectangular rule
rect_2(i)=h(i)*sum(g(y2)); % Rectangular rule after applying change of variables
end
error_rect_1 = abs(double(rect_1 - exact_int)); % absolute error using Rectangular rule
error_rect_2 = abs(double(rect_2 - exact_int)); % absolute error using Rectangular rule after applying change of variables
figure;
loglog(h,error_rect_1,'r','linewidth',1);
hold on
loglog(h,error_rect_2,'b','linewidth',1);
xlabel('Gridspacing');
ylabel('Error');
legend('Recangular rule' ,'Rectangular rule after applying change of variables','location','southeast','FontSize',7,...
'FontWeight','bold','Color','y');
Answers (0)
Categories
Find more on Linear Algebra 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!