Vous êtes sur la page 1sur 2

%Integration

%The input file is A4_Input1.txt and is inside the given folder, and the
%sample input is currently stored inside it. Kindly change the data inside
%that input file if you want to try out some other input.
fileIP = fopen('A4_Input1.txt','r');
A = fgetl(fileIP);
B = fscanf(fileIP,'%s',1);
a = str2double(B(1));
b = str2double(B(3));
e = fscanf(fileIP,'%f',1);
met = fscanf(fileIP,'%d',1);
for i = 1:length(A);
if A(i)=='=';
func = A(1,i+1:length(A));
end
end
f = str2func(['@(x)',func]);%assuming the function variable to be x!

method = menu('Choose the method to evalutate the integral: ','Romberg


Integration','Gauss-Legendre Quadrature');
disp('Your Output is stored in the file named A4_Output1.txt');

switch (method)
case 1
%Romberg Integration
h = b-a;
I = zeros(1,100);
I(1) = h*(f(a)+f(b))/2;
err = 1;
for j = 2:100
h = h/2;
for i = a:h:b-h
I(j) = I(j) + h*(f(i)+f(i+h))/2;
end
for i = j:-1:2
I(i-1) = (I(i)*4^(j-i+1) - I(i-1))/(4^(j-i+1)-1);
end
err = (I(1)-I(2))*100/I(1);
if abs(err)<e
break;
end
end

%plotting graph and Output -


figure
title('Romberg Algorithm')
hold on
for p = a:h:b
plot(p,f(p),'o','MarkerFaceColor','black')
end
hold off
fileOP = fopen('A4_Output1.txt','w');
fprintf(fileOP,'%s%.8f\n','I = ',I(1));
fprintf(fileOP,'%s%d\n','Number of Intervals = ',j);
fprintf(fileOP,'%s%f\n','Approximate Relative Error = ',err);
fclose(fileOP);
case 2
%Gauss-Legendre Quadrature
err = 1;
i = 1; % ith point quadrature
I = (b-a)*f((b+a)/2); %1 point quadrature
while err>e
i = i + 1;
syms y
Z = vpasolve(legendreP(i,y) == 0);%zeros of the legendre polynomial
C = zeros(i,1);%weights of the polynomial
for j = 1:i
C(j) = 2*(1-Z(j)^2)/(i*legendreP(i-1,Z(j)))^2;
end%calculating the weights
J = I;I = 0;
X = (Z*(b-a) + (b+a))/2;
for k = 1:i
I = I + C(k)*f(X(k));
end
I = (b-a)*I/2;
err = abs((I-J)/I)*100;
end

%plotting graph and Output -


figure
title('Gauss Legendre Quadrature')
hold on
for p = 1:k
plot(X(p),f(X(p)),'o','MarkerFaceColor','black')
end
hold off
fileOP = fopen('A4_Output1.txt','w');
fprintf(fileOP,'%s%.8f\n','I = ',I(1));
fprintf(fileOP,'%s%d\n','Number of Gauss Points = ',i);
fprintf(fileOP,'%s%f\n','Approximate Relative Error = ',err);
fclose(fileOP);
end

Vous aimerez peut-être aussi