Compute the definite integral shown below using the Rectangl
Solution
Following is the required matlab code:
clc; clear;
%rectangle method
 a = 0;
 b = 2*pi;
 Error = zeros( 500, 1 );
 Ns = zeros( 500, 1 );
for N=5:500
     h = (b - a)/N;
     answer = 0;
     xn = a;
     for i=0:N-1
         %find value of x*sin(x) for xn
         answer = answer + xn*sin(xn);
         xn = xn + h;
     end
     answer = answer*h;
   
     relativeError = abs((-2*pi) - answer)/abs(-2*pi);
    Error(N, 1) = log(relativeError); %using logarithmic scale
     Ns( N, 1 ) = N;
 end
 figure;
 plot( Ns(5:end) , Error(5:end) );
 title(\'log(Relative Error), using rectangle method vs N\');
 xlabel(\'N\');
 ylabel(\'log(Relative Error)\');
%trapezoidal method
 a = 0;
 b = 2*pi;
 Error = zeros( 500, 1 );
 Ns = zeros( 500, 1 );
for N=5:500
     h = (b - a)/N;
     answer = 0;
     xk = a;
     xkplus1 = a + h;
     for i=0:N-1
         answer = answer + ( xk*sin(xk) + xkplus1*sin(xkplus1) );
         xk = xkplus1;
         xkplus1 = xkplus1 + h;
     end
     answer = answer*(h/2);
   
     relativeError = abs((-2*pi) - answer)/abs(-2*pi);
    Error(N, 1) = log(relativeError); %using logarithmic scale
     Ns( N, 1 ) = N;
 end
 figure;
 plot( Ns(5:end) , Error(5:end) );
 title(\'log(Relative Error), using trapezoidal method vs N\');
 xlabel(\'N\');
 ylabel(\'log(Relative Error)\');


