Solution for Ex 1. At rst write the function TrapezioComposto 1 function [I] = TrapezioComposto(f,a,b,x2,m)
2 % x2 are the quadrature nodes
3 % a,b,m used only for the equispaced case (eventually) 4 I=(f(x2(2:end))+f(x2(1:end−1)))*(x2(2:end)−...
5 x2(1:end−1))'/2;
6 % Note that if we limit (as for the theory) 7 % to equispaced nodes, then the program 8 % simplifies
Then, on the script named Esercizio1 do the following 1 clear all; close all;
2 f=@(x) sqrt(1−x.^2); toll=1.e−3; maxit=1000;
3 err=1; N=3; a =0; b =1; % initialize 4 Itrue = quad(f,0,1);
5 while (err>toll) && (N<maxit) 6 x2=linspace(0,1,N);
7 I1=TrapezioComposto(f,a,b,x2,N−1);
8 err=abs(Itrue−I1);
9 N=N+1;
10 end
11 sprintf('Iter numb for equispaced = %d',N−1) 12 N = 3; err=1; % initialize
13 while (err>toll) && (N<maxit)
14 x2=1/2−cos([0:N−1]*pi/(N−1))/2; %Cheb−Lob points 15 I1=TrapezioComposto(f,a,b,x2,N−1);
16 err=abs(Itrue−I1);
17 N=N+1;
18 end
19 sprintf('Iter numb for CL = %d',N−1)
1
Solution for Ex 2. At rst write the function SimpsonComposto 1 function [x,w] = SimpsonComposto(N,a,b)
2 % it calculates nodes and weights of the Simpson rule 3 h=(b−a)/(2*N); % step
4 x=a:h:b ; x=x' ; % equispaced nodes 5 w=zeros(2*N,1) ; % initialize
6 w(1)=h/3; % first weight 7 w(2*N+1)=h/3; % last weight 8 % even weights
9 ind_pari = 2:2:2*N ; 10 w(ind_pari)=4*h/3;
11 % odd weights
12 ind_disp = 3:2:2*N−1;
13 w(ind_disp)=2*h/3;
Then, on the script named Esercizio2 do the following 1 clear all
2 close all
3 f=@ (x) 1./(1+x) ; 4 a=0; b=1;
5 sol=log(2) ; %true solution 6 N = 5;
7 [x,w]= SimpsonComposto(N,a,b) ; 8 S_CS=sum(w.*f(x));
9 disp('Error') 10 abs(S_CS−sol)
2